所以我在数据库里面有2个表。第一个是名称映射的唯一ID
Customers
UID | CustomerName
在第二个表中,我有类似下面的内容
Orders
OrderNum | CustomerID | CustomerID2
现在我想插入订单,但我只有2个客户名称的名称,所以我想象下面的东西(不起作用)
insert into Orders select null, UID as id1, UID as id2 from Customers where CustomerName=="sven";
如何从第一张表中获取两个UID?
此外,我需要能够反过来并从表中选择
SELECT * FROM Orders a JOIN (Customers b) ON a.UID=b.UID WHERE b.CustomerName='sven'
这些都不起作用,我似乎无法在网上找到类似的东西。
答案 0 :(得分:1)
更新:根据您的评论,如果您尝试将两个不同客户'ID插入一个订单,则可以执行
INSERT INTO Orders (CustomerID, CustomerID2)
SELECT c1.uid uid1, c2.uid uid2
FROM
(
SELECT uid
FROM customers
WHERE customername = 'sven'
LIMIT 1
) c1 CROSS JOIN
(
SELECT uid
FROM customers
WHERE customername = 'jhon'
LIMIT 1
) c2
选择其中一个客户存在的订单
SELECT o.*
FROM orders o LEFT JOIN customers c1
ON o.customerid = c1.uid LEFT JOIN customers c2
ON o.customerid2 = c2.uid
WHERE c1.customername IN('sven', 'jhon')
OR c2.customername IN('sven', 'jhon')
这是 SQLFiddle 演示
原始回答:您在寻找这个吗?
要插入
INSERT INTO Orders (CustomerID, CustomerID2)
SELECT c1.uid uid1, c2.uid uid2
FROM customers c1 LEFT JOIN customers c2
ON c1.customername = c2.customername
AND c1.uid < c2.uid
WHERE c1.customername = 'sven'
LIMIT 1
选择
SELECT o.*
FROM orders o LEFT JOIN customers c1
ON o.customerid = c1.uid LEFT JOIN customers c2
ON o.customerid2 = c2.uid
WHERE c1.customername = 'sven'
OR c2.customername = 'sven'
这是 SQLFiddle 演示
答案 1 :(得分:0)
要从另一个表插入一个表,请使用this syntax:
INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
[INTO] tbl_name [(col_name,...)]
SELECT ...
[ ON DUPLICATE KEY UPDATE col_name=expr, ... ]
因此,在您的情况下,您的查询应该是:
INSERT INTO Orders (CustomerID, CustomerID2)
SELECT UID, UID
FROM Customers WHERE CustomerName = 'sven';
如果您想从单个查询中插入多条记录,可以使用IN
运算符代替=
,如下所示:
INSERT INTO Orders (CustomerID, CustomerID2)
SELECT UID, UID
FROM Customers WHERE CustomerName IN ('sven', 'smith');
您加入SELECT
查询时出错:
在UID
表格中没有UID
的情况下,您使用Orders
加入了两个表格。可能是你的意思CustomerID
。试试这个:
SELECT * FROM Orders a
JOIN Customers b
ON a.CustomerID = b.UID
WHERE b.CustomerName='sven'