我试图从多个不同的表中插入多个值的表。这是一个简单的例子(在实践中,这将是无用的,但如果我发布完整的查询,理解起来会更复杂):
CREATE TABLE person (
id INT PRIMARY KEY,
lastName VARCHAR(100),
firstName VARCHAR(50),
dob DATE,
telNo VARCHAR(20)
);
CREATE TABLE postcode (
id INT PRIMARY KEY,
postcode VARCHAR(10),
);
CREATE TABLE name (
id INT PRIMARY KEY,
lastName VARCHAR(100),
firstName VARCHAR(50)
);
INSERT INTO postcode VALUES(21, "DN3 1SU");
INSERT INTO name VALUES(21, "Smith", "John");
INSERT INTO person (id, lastName, firstName, dob, telNo) VALUES (
(SELECT id FROM postcode WHERE postcode="DN3 1SU"),
(SELECT lastName, firstName FROM name WHERE id=21),
"1991-12-20",
"075935678923"
);
我基本上是在尝试根据其他表中的数据构建一个新行(我从每个表中获取的列数不同)和一些文字值。
使用我目前使用的方法,VALUES不接受第二个SELECT语句,因为它提供了两列,而不是一列。
答案 0 :(得分:1)
只需使用INSERT ... SELECT
追加查询:
INSERT INTO `person` (id, lastName, firstName, dob, telNo)
SELECT p.id, n.lastName, n.firstName, '1991-12-20', '075935678923'
FROM `postcode` p
INNER JOIN `name` n ON p.id = n.id AND n.id = 21
WHERE p.postcode = 'DN3 1SU'
答案 1 :(得分:0)
使用JION操作将所有数据(要插入的数据)收集到一个位置,然后使用INSERT命令。
INSERT INTO person (id, lastName, firstName, dob, telNo)
(
SELECT t2.id, t2.lastName, t2.firstName, t2.aa, t2.bb
from
(SELECT id FROM postcode WHERE postcode="DN3 1SU") t1
INNER JOIN
(SELECT id,lastName, firstName, '1991-12-20' as aa, '075935678923' as bb FROM name WHERE id=21) t2
ON t1.id=t2.id
);
答案 2 :(得分:0)
如果您的条件允许,这应该有效。您有五列要填充,您需要用逗号分隔5个值。
INSERT INTO table1 (val1, val2, val3, val4, val5) VALUES (
(SELECT val1 FROM table2 WHERE condition),
(SELECT val2 FROM table3 WHERE condition),
(SELECT val3 FROM table3 WHERE condition),
"literal1",
"literal2"
);