我有一个包含两个表的数据库。当用户发布一篇文章时,它将被插入两个表中,(一个文件中有两个查询(
我使用post_id
作为foreign key
,两个表post_id
都自动递增。外国钥匙会被弄乱吗?例如,如果用户A和B同时查询数据库。
表1
post_id user...
1 A
2 B
表2
post_id content...
1 A
2 B
首先,不能在两个表上都自动递增。
通常,您所做的是table 1
中的insert
,获得刚刚插入的行的ID
。
然后使用这个ID
,到引用table 1
的table 2
中的insert
。
请参阅上的mysqli::$insert_id
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);
您也可以使用基于以下内容的存储过程来完成此操作: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');
为什么不将table1用作用户表,将second用作posts?
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