简体   繁体   English

将主要ID保存在MySQL表的另一列中

[英]Save primary ID in another column in MySQL Table

i have this MySQL Table: 我有这个MySQL表:

    CREATE TABLE web_media_com (
    web_media_id INT AUTO_INCREMENT PRIMARY KEY,
    web_media_position INT(12),
    web_media_headline VARCHAR(76),
    web_media_description VARCHAR(680)
    );

I would like to add the primary id to the "web_media_position" in one INSERT INTO query. 我想在一个INSERT INTO查询中将主ID添加到“ web_media_position”中。 So when "web_media_id" gets the id 234 then "web_media_position" should get the same 234 number. 因此,当“ web_media_id”获得ID 234时,“ web_media_position”应获得相同的234号。

Right now i have this: 现在我有这个:

    $mysql_query = "INSERT INTO `web_media_com` (web_media_position, web_media_headline, web_media_description) VALUES
    (LAST_INSERT_ID(), '".$web_media_headline."', '".$web_media_description."')";

But this does not work. 但这是行不通的。 Can someone please tell me how i can do This? 有人可以告诉我我该怎么做吗? thanks!!! 谢谢!!!

Use a transaction to prevent conflicts between concurrent inserts. 使用事务来防止并发插入之间发生冲突。

In straight (non PHP) sql it would look something like: 在直接(非PHP)sql中,它将类似于:

START TRANSACTION;
   INSERT INTO web_media_com(columns)....
   SET @entry_id = LAST_INSERT_ID();
   UPDATE web_media_com set web_media_position = @entry_id 
      where web_media_id = @entry_id;
COMMIT;

(NOTE: I didn't try this is in a fiddle.. YMMV...) (注意:我没试过这是摆弄。YMMV ...)

Best Solution For You 最适合您的解决方案

$mysql_query =
 "INSERT INTO web_media_com 
    (web_media_position, web_media_headline, web_media_description) 
    select MAX('id')+1,'".$web_media_headline."','".$web_media_description."' 
      from web_media_com";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM