在相关表中插入mysql [英] insert in a related table mysql
本文介绍了在相关表中插入mysql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个MySQL表(InnoDB).我创建了一个 users
表,其中"id_users"作为关系键.然后,我创建了第二个表,该表在 users
表中具有对"id_users"的外键引用.如何在第二张表中插入MySQL?
I have two MySQL tables (InnoDB). I have created a users
table with "id_users" as the relationship key. Then I created a second table with a foreign key reference to "id_users" in the users
table. How can I do a MySQL Insert into the second table?
我应该使用JOIN吗?
Should I use JOIN?
推荐答案
联接仅用于 SELECT
语句.您只需要做两个简单的插入即可:
Join is only for SELECT
statement. What you want to do is just two simple inserts :
- 将行插入用户
- 获取用户的最后一个ID
- 将外键等于最后一个id插入第二个表中的行.
在mysql中,可以是:
In mysql, this can be :
INSERT INTO user (id, username) VALUES (NULL, 'john');
INSERT INTO group (id, id_users) VALUES (NULL, LAST_INSERT_ID())
LAST_INSERT_ID
适用于整个数据库...请谨慎使用.
LAST_INSERT_ID
works for the entire database... be carefull using it.
这篇关于在相关表中插入mysql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文