如何获取 MySQL 中最后更新行的 ID? [英] How to get ID of the last updated row in MySQL?

查看:25
本文介绍了如何获取 MySQL 中最后更新行的 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 PHP 获取 MySQL 中最后更新行的 ID?

How do I get the ID of the last updated row in MySQL using PHP?

推荐答案

我已经找到了这个问题的答案 :)

I've found an answer to this problem :)

SET @update_id := 0;
UPDATE some_table SET column_name = 'value', id = (SELECT @update_id := id)
WHERE some_other_column = 'blah' LIMIT 1; 
SELECT @update_id;

编辑 by aefxx

可以进一步扩展此技术以检索受更新语句影响的每一行的 ID:

This technique can be further expanded to retrieve the ID of every row affected by an update statement:

SET @uids := null;
UPDATE footable
   SET foo = 'bar'
 WHERE fooid > 5
   AND ( SELECT @uids := CONCAT_WS(',', fooid, @uids) );
SELECT @uids;

这将返回一个字符串,其中所有 ID 用逗号连接.

This will return a string with all the IDs concatenated by a comma.

这篇关于如何获取 MySQL 中最后更新行的 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆