我们什么时候给 LAST_INSERT_ID() 一个参数?
引自此处:
mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1);
mysql> SELECT LAST_INSERT_ID();
的用例是什么上面的(有什么好处)?
我以前从未将 LAST_INSERT_ID 与任何参数一起使用过...
更新
我的问题是为什么人们想要以这种方式模拟这种序列,当它自动可用时框通过自动递增主键?
Quoted from here:
mysql> UPDATE sequence SET id=LAST_INSERT_ID(id+1);
mysql> SELECT LAST_INSERT_ID();
What's the use case of the above (what's the benefit )?
I've never used the LAST_INSERT_ID with any parameter before...
UPDATE
My question is why one wants to simulate such kind of sequence this way, when it's automatically available out of the box by auto-incremented primary key?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不使用 AUTO_INCRMENT 生成序列的一种用例是当生成的 ID 值在多个表中使用时,并且它需要在所有表中是唯一的。每个表中的 AUTO_INCRMENT 通常会导致每个表中存在相同的值。
不考虑正常形式的要求,一个例子可以来自教室。每次考试都需要一个唯一的 ID,但考试记录在多个表中:临时测验、每周测试、期中考试和期末考试。使用 OP 提供的引用可以生成 ID 序列,该序列可用于保持 ID 在所有表中唯一。
A use-case for generating the sequence without the use of AUTO_INCREMENT would be when the resultant ID value is used in more than one table, and it needs to be unique across all the tables. An AUTO_INCREMENT in each table could, most often would, result in the same value existing in each table.
Disregarding normal form requirements, an example could be from a classroom. Every exam given needs a unique ID, yet the exams are recorded in multiple tables: Pop-quizes, weekly tests, mid-term exams, and final exams. Using the OP-provided quote allows the generation of an ID sequence which can be used to be keep the ID unique across all the tables.
还引用此处:
Also quoted from here:
上面给出的查询是更新查询,查询只是更改之前行中的 id。
它只是更新行 ID,因此需要像这样更新它。
用户可能希望在对其进行一些处理后更改结果行的索引。
LAST_INSERT_ID 将返回最后插入的 id。仅当用户想要将行的索引从前一行更改为结果集中最新的行时,才会出现这种情况。
Query given above is update query and query is just changing the id which was in the row before.
Its just updating a rows id so it is needed to update it like this way.
Might be user want to change the index of the result row after some work on it.
LAST_INSERT_ID will return the last id inserted. And this will be the case only if user want to change the index of the row from the previous one to the one which will be latest in result set.