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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置