我有两个表 hello
和 login_table
下面是它们的结构
user_info
-------
some_id | name | address
login_table
-------
id | username | password
some_id
和 id
是自增索引。
现在我如何在 SQL
中使用 INSERT
语句和 INNER JOIN
目前,我想添加以下具有相同 some_id
和 id
的数据
`name` = John
`address` = wall street
`username` = john123
`password` = passw123
下面的代码显示了我到目前为止所做的尝试。
insert into login_table lt
INNER JOIN user_info ui ON ui.some_id = lt.id
(ui.name, ui.address, lt.username, lt.password)
values
('John', 'wall street', 'john123', 'passw123')
这不是一个值,我想一次添加多个值..我怎样才能实现。
感谢帮助。
最佳答案
如果您需要以原子方式执行两个INSERT
操作,请使用事务:
START TRANSACTION;
INSERT INTO login_table (username, password) VALUES ('john123', 'passw123');
INSERT INTO user_info (name, address) VALUES ('John', 'wall street');
COMMIT;
注意您的存储引擎必须支持事务才能工作(例如 InnoDB
)。
要一次将多个值插入到表中,请使用 INSERT
的多行形式。如 the manual 中所述:
INSERT
statements that useVALUES
syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas. Example:INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);The values list for each row must be enclosed within parentheses. The following statement is illegal because the number of values in the list does not match the number of column names:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3,4,5,6,7,8,9);
VALUE
is a synonym forVALUES
in this context. Neither implies anything about the number of values lists, and either may be used whether there is a single values list or multiple lists.
关于INNER JOIN 一次用于两个表的 SQL INSERT 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10617239/