【问题标题】:Insert into 2 table and set both foreign key auto increment插入2个表并设置两个外键自动增量
【发布时间】:2013-06-03 12:35:44
【问题描述】:

我有一个包含两个表的数据库。当用户发布一篇文章时,它将被插入到两个表中,(一个文件中有两个查询)

我使用post_id 作为foreign key,两个表post_id 自动递增。外键会乱吗?例如,如果用户 A 和 B 同时查询数据库。

表 1

post_id user...
1       A
2       B

表 2

post_id content...
1       A
2       B

【问题讨论】:

  • 一个表中只能有 1 个自增字段。改用联接

标签: php mysql


【解决方案1】:

首先你不能在两个表上都自动递增。

通常,你所做的就是table 1中的insert,获取刚刚插入的行的ID

然后你使用这个ID,到insert 中的table 2 引用table 1

参见:mysqli::$insert_id at

http://www.php.net/manual/en/mysqli.insert-id.php

示例:

$query = "INSERT INTO table1(user,whatever) VALUES ('A','something')";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

$query = "INSERT INTO table2(post_id,content) VALUES ($mysqli->insert_id,'This is content')";
$mysqli->query($query);

【讨论】:

  • 所以我必须使用最后一个插入 id 并在之后查询
  • 完全正确...并且第二张桌子上没有自动增量。
  • 更好的是,您还可以使用此处描述的存储过程以满足您的需求:stackoverflow.com/a/1723325/1688441
【解决方案2】:

您也可以使用基于以下内容的存储过程:stackoverflow.com/a/1723325/1688441

DELIMITER //
CREATE PROCEDURE new_post_with_content(
  user_id CHAR(5), content_text CHAR(100)
BEGIN
START TRANSACTION;
   INSERT INTO table1 (user) 
     VALUES(user_id);

   INSERT INTO table2 (post_id, content) 
     VALUES(LAST_INSERT_ID(), content_text);
COMMIT;
END//

DELIMITER ;

你这样称呼它:

CALL new_engineer_with_task('A','This is the content');

【讨论】:

    【解决方案3】:

    为什么不使用 table1 作为用户表,第二个用于帖子?

    users
    user_id(autoinc)    username
    1                   A
    2                   B
    3                   C
    
    posts
    post_id(autoinc)   user_id       posts_text
    1                  2             text
    2                  1             other text
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 2014-10-11
      • 2018-03-21
      • 2013-04-25
      • 2019-05-05
      • 2015-06-09
      相关资源
      最近更新 更多