选择最后一个 id,不插入
我正在尝试检索一个表 A 的 id 以插入到另一个表 B 中。我无法使用 last_insert_id(),因为我没有在 A 中插入任何内容。关于如何很好地做到这一点有什么想法吗?
$n = mysql_query("SELECT max(id) FROM tablename");
似乎不起作用,也不起作用
$n = mysql_query("SELECT max(id) FROM tablename GROUP BY id");
I'm trying to retrieve the id of one table A to insert into another table B. I cannot use last_insert_id() as i have not inserted anything into A. Any ideas on how to do this nicely?
$n = mysql_query("SELECT max(id) FROM tablename");
doesn't seem to work, nor does
$n = mysql_query("SELECT max(id) FROM tablename GROUP BY id");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 MySQL 中,这确实返回
id
列中的最高值:但是,这不会将该 id 放入
$n
中:要获取该值,您需要执行以下操作:
如果你想从A中获取最后一次插入的ID,并将其插入到B中,你可以用一条命令来完成:
In MySQL, this does return the highest value from the
id
column:However, this does not put that id into
$n
:To get the value, you need to do this:
If you want to get the last insert ID from A, and insert it into B, you can do it with one command:
您可以按 id 对表进行降序排序,并将结果数量限制为 1:
BUT
ORDER BY
会为此请求重新排列整个表。所以如果你有很多数据并且需要多次重复这个操作,我不会推荐这个解决方案。You could descendingly order the tabele by id and limit the number of results to one:
BUT:
ORDER BY
rearranges the entire table for this request. So if you have a lot of data and you need to repeat this operation several times, I would not recommend this solution.我有不同的解决方案:
I have different solution:
您可以获取最大列值并递增它< /a>:
您也可以使用 显示表状态 及其“Auto_increment”值。
You can get maximum column value and increment it:
Also you can use SHOW TABLE STATUS and its "Auto_increment" value.
我想为每条记录添加时间戳并获取最新的。在这种情况下,您可以获得任何 id、打包行和其他操作。
I think to add timestamp to every record and get the latest. In this situation you can get any ids, pack rows and other ops.
或者
or