dongru2019 2018-07-13 10:41
浏览 141
已采纳

有没有办法更新行以添加批次ID并返回该ID?

I'd like to retrieve a number of rows from a MySQL table, and remember which ones I've retrieved later. (I'm sending these to an API and I need to track whether they were accepted or not).

The way I'd like to achieve this is to use an UPDATE query in order to create a batch_id for 100 records or so. I'd also like to get the batch_id returned.

Here's what I've come up with so far (complete PHP function):

function get_batch() {
    global $DB;
    $q = $DB->prepare("UPDATE my_table 
                       SET batch_id = LAST_INSERT_ID(MIN(id)) 
                       WHERE batch_id = ''
                       LIMIT 100");
    $q->execute();
    return $DB->lastInsertId();
}

This is an invalid use of a group function (because I can't use MIN on all rows at the same time as updating individual rows, presumably).

I could use a subquery to find the lowest ID, but I wondered if there was a better way of doing this?

I'm also not sure if my use of LAST_INSERT_ID is correct in this context (setting it to retrieve it later)?

  • 写回答

2条回答 默认 最新

  • douduan9129 2018-07-13 12:42
    关注

    In the end, the best solution I could come up with, was the following:

    function get_batch() {
        global $DB;
        $q = $DB->prepare("UPDATE my_table
                           SET batch_id = (
                             SELECT batch_id FROM (
                               SELECT LAST_INSERT_ID(MIN(id)) AS batch_id
                               FROM my_table WHERE (batch_id = 0)
                             ) b
                           )
                           WHERE batch_id = 0 ORDER BY id LIMIT 100");
        $q->execute();
        return $DB->lastInsertId();
    }
    

    Note that the sub query required another sub query within (b), which is something to do with getting MySQL to copy the sub query result to a separate table space (related question).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化