0

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

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

表格1

post_id user...
1       A
2       B

表 2

post_id content...
1       A
2       B
4

3 回答 3

3

首先,您不能在两个表上都有自动增量。

通常,您所做的是insert在 中table 1,获取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);
于 2013-06-03T12:37:24.630 回答
0

您也可以使用基于以下内容的存储过程执行此操作: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');
于 2013-06-03T12:53:07.473 回答
0

为什么不将 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
于 2017-05-24T15:55:34.340 回答