更新:根据您的评论,如果您尝试将两个不同客户的 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演示