如何在 MySQL 中获取多个插入行的 ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7501464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the ID of multiple inserted rows in MySQL?
提问by Googlebot
I am inserting some words into a two-column table with this command:
我正在使用以下命令将一些单词插入到一个两列的表中:
INSERT IGNORE INTO terms (term) VALUES ('word1'), ('word2'), ('word3');
How can I get the ID (Primary Key) of the row in which each word is inserted. I mean returning a value like "55,56,57" after executing
INSERT
. Does MySQL have such a response?The term column is
UNIQUE
. If a term already exists, MySQL will not insert it. Is it possible to return the reference for this duplication (i.e. the ID of the row in which the term exists)? A response like "55,12,56".
如何获取插入每个单词的行的 ID(主键)。我的意思是在执行后返回一个像“55,56,57”这样的值
INSERT
。MySQL有这样的反应吗?术语列是
UNIQUE
。如果一个术语已经存在,MySQL 不会插入它。是否可以返回此重复项的引用(即该术语所在行的 ID)?像“55, 12,56”这样的响应。
采纳答案by glglgl
You get it via
SELECT LAST_INSERT_ID();
or via having your framework/MySQL library (in whatever language) callmysql_insert_id()
.That won't work. There you have to query the IDs after inserting.
您可以通过
SELECT LAST_INSERT_ID();
或通过让您的框架/MySQL 库(以任何语言)调用mysql_insert_id()
.那行不通。在那里你必须在插入后查询 ID。
回答by mellamokb
Why not just:
为什么不只是:
SELECT ID
FROM terms
WHERE term IN ('word1', 'word2', 'word3')
回答by Nugget
First, to get the id just inserted, you can make something like :
首先,要获取刚刚插入的 id,您可以执行以下操作:
SELECT LAST_INSERT_ID() ;
Care, this will work only after your last INSERT
query and it will return the first ID onlyif you have a multiple insert!
请注意,这仅在您最后一次INSERT
查询之后有效,并且只有在您有多个插入时才会返回第一个 ID!
Then, with the IGNORE
option, I don't think that it is possible to get the lines that were not inserted. When you make an INSERT IGNORE
, you just tell MySQL to ignore the lines that would have to create a duplicate entry.
然后,使用该IGNORE
选项,我认为不可能获取未插入的行。当您创建一个 时INSERT IGNORE
,您只需告诉 MySQL 忽略必须创建重复条目的行。
If you don't put this option, the INSERT
will be stopped and you will have the line concerned by the duplication.
如果您不放置此选项,INSERT
则将停止,并且您将拥有与重复相关的行。