[英]MySQL Insert row with column value same as Auto Increment
The id column is auto increment. id列是自动增量。 I want the "rank" column to have the same value as the newly generated auto increment value from the "id" column.
我希望“rank”列与“id”列中新生成的自动增量值具有相同的值。 (eg. say the next auto increment value is 999... I want the rank to equal this too)
(例如,说下一个自动增量值是999 ......我也希望排名等于这个)
Can I do this in one query? 我可以在一个查询中执行此操作吗? OR do I have to run an additional query to get the auto increment value before
或者我是否必须运行其他查询才能获得自动增量值
$query = "INSERT INTO $table1(id,name,rank)
VALUES('','bob','999')";
You can get actual auto_increment value in one insert using this query: 您可以使用此查询在一个插入中获取实际的auto_increment值:
insert into tablename (name,rank) values ( 'bob',(SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'tablename'
AND table_schema = DATABASE( ) ) )
See more here - How to get the next auto-increment id in mysql 在这里查看更多 - 如何在mysql中获取下一个自动增量ID
last_insert_id()
is only set AFTER the insert completes (successfully or not). last_insert_id()
仅在插入完成后设置(成功与否)。 If you try something like 如果你尝试类似的东西
INSERT INTO yourtable (id, dupe_id) VALUES (null, last_insert_id())
and hoping that dupe_id
gets the same ID that'll be assigned to id
, then... no, it won't. 并希望
dupe_id
获得将被分配给id
的相同ID,然后......不,它不会。 last_insert_id()
will return the ID creatd by whatever insert was run BEFORE this particular statement. last_insert_id()
将通过在此特定语句之前运行的任何插入返回ID creatd。
You'll have to do (basically): 你必须(基本上):
INSERT ...;
UPDATE yourtable SET dupe_id=last_insert_id() WHERE id=last_insert_id();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.