[英]SQL insert into select from multiple fields
I have a table 'users' with a column of 'ID'. 我有一个'用户'表,其中包含'ID'列。 I want to select 2 different 'ID's' based on 2 different parameters and insert them both into another table known as 'jobs'.
我想根据2个不同的参数选择2个不同的“ID”,并将它们插入另一个称为“作业”的表中。
INSERT INTO jobs (customer_id, client_id)
SELECT id, id from users
WHERE username = ?
AND username = ?
Basically I want to get the ID of two different people and insert them both into the new table. 基本上我想获得两个不同人的ID并将它们都插入到新表中。
I would then bind the parameters to ?, and they would look something like 'john' and 'steve'. 然后我将参数绑定到?,它们看起来像'john'和'steve'。 I have tried the code above but I know it is the wrong syntax.
我已经尝试过上面的代码,但我知道这是错误的语法。 Any ideas would be greatly appreciated.
任何想法将不胜感激。 Thanks
谢谢
You could use a self-join: 您可以使用自联接:
INSERT INTO jobs
(customer_id, client_id)
SELECT customer.id, client.id
FROM users customer
JOIN users client ON customer.username = ? AND client.username = ?
Or, you could use subqueries: 或者,您可以使用子查询:
INSERT INTO jobs
(customer_id, client_id)
VALUES (
(SELECT id FROM users WHERE username = ?),
(SELECT id FROM users WHERE username = ?)
)
Well, you could use subquerys 好吧,你可以使用subquerys
INSERT INTO jobs (customer_id, client_id)
VALUES (
(SELECT field from table where id = 2),
(SELECT field from table2 where id = 12)
)
I'm not pretty sure about the sintax, since I haven't tested, but I'm guessing it could solve it. 我不太确定sintax,因为我没有测试过,但我猜它可以解决它。
I often use such things in WHERE or in the SELECT statement. 我经常在WHERE或SELECT语句中使用这些东西。 Just remember to return a single field and a single row in the subquerys.
只记得在subquerys中返回一个字段和一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.