0

所以我在数据库中有 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'

这些都不起作用,我似乎无法在网上找到类似的东西。

4

2 回答 2

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演示

于 2013-07-12T05:22:48.967 回答
0

要从另一个表插入一个表,请使用以下语法

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没有。可能是你的意思。试试这个:UIDOrdersCustomerID

SELECT * FROM Orders a 
  JOIN Customers b 
    ON a.CustomerID = b.UID 
 WHERE b.CustomerName='sven'

看到这个 SQLFiddle

于 2013-07-12T05:15:53.610 回答