MySQL获取刚刚插入的行 [英] Mysql fetch the row just inserted

查看:56
本文介绍了MySQL获取刚刚插入的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在设计一个将行插入MySQL数据库的函数.该表具有一个启用了自动增量的主键.因此,我不会插入此列的值.但是PK是整个表格中唯一的唯一列.如何获取刚刚插入的行?

So I'm designing a function that inserts a row into the MySQL database. The table has a Primary key with Auto-Increment enabled. So I don't insert the value of this column. But the PK is the only unique column of the entire table. How can I fetch the row I just inserted?

如果该函数的流量很小,我看不到任何问题,但是当它的负载越来越重时,我可以看到一个潜在的错误:说我插入一行并且DB的AI值为1,然后在fetch函数开始请求最新插入的行",另一行将插入AI值2.现在,如果运行Insert 1的fetch函数,则将提取第2行.我知道时间间隔必须很小,才能使此错误实际存在,但是有没有更好的方法来获取正确的行,同时又只将PK作为唯一列来维护表呢? (尽管我认为这是一个潜在的解决方案,但我不想实现额外的校验和列.)

I don't see a problem if the function is in light traffic, but when its load is heavier and heavier, I can see a potential bug: say I inserted a row and the DB's AI value is 1, then before the fetch function starts to request the "latest inserted row", another row is inserted with the AI value 2. Now if the fetch function of Insert 1 runs, Row 2 will be fetched. I know the time gap will need to be so small to allow this bug to actually exist, but is there a better way to fetch the right row, while maintain the table only having the PK as the unique column? (I don't want to implement an additional checksum column, though I see it's a potential solution.)

推荐答案

它不是很合逻辑,但是您可以:

its not very logical but you could:

insert into `table1` (`column1`,`column2`,`column3`) VALUES ("value1","value2","value3");
select * from `table1` where `PK`=LAST_INSERT_ID();

相反,您仅应按照建议的SELECT LAST_INSERT_ID();并重用其他数据

instead you should only SELECT LAST_INSERT_ID(); as jurgen d suggested and reuse the other data

这篇关于MySQL获取刚刚插入的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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