MySQL在子查询中引用外部选择

时间:2014-04-03 19:07:07

标签: mysql select reference subquery

我有两张桌子,货物和客户。我想用货物打印出客户的姓氏。表格设置为:

shipments:  shipNumber, shipperID, destID, size, weight

shipperID和destID是来自customers表的外键。

customers:  id, lastName, street, city, state, zip.

当我查询时,我想要的是这样的表:

shipNumber, shipperID(customers.id), customer.lastName, destID(customers.id), customer.lastName

shipperID和destID不相同,因此customers.lastName字段只应与它们之后的id字段相关。

我当前的查询由于显而易见的原因无效:

SELECT shipments.shipNumber, shipments.shipperID, customers.lastName, shipments.destID, 
(SELECT customers.lastName 
FROM shipments, customers 
WHERE shipments.destID = customers.id)

FROM shipments, customers
WHERE shipments.shipperID = customers.id;

我的子查询显然会打印多行,但我希望destID引用的客户的姓氏与发货编号相关,但我知道mySQL会查看内部的查询。

示例数据:

shipments table
+------------+-----------+---------+------+--------+
| shipNumber | shipperID | destID  | size | weight |
+------------+-----------+---------+------+--------+
| S12345-0   | W-100     | C-22315 |   12 |     12 | 
| SYY89-4    | C-15572   | U-01002 |   12 |     12 | 
+------------+-----------+---------+------+--------+

customers table
+---------+------------------+
| id      | lastName         |
+---------+------------------+
| S-01210 | Home Depot       | 
| S-18537 | Honda            | 
| S-13349 | NCR              | 
| C-15572 | GM               | 
| C-00122 | Delco            | 
| W-100   | Warehouse A      | 
| U-01002 | Wright State     | 
| W-210   | Warehouse B      | 
| U-00013 | AFIT             | 
| C-22315 | Northrop Grumman | 
+---------+------------------+

我想要查询显示的内容:

shipNumber    shipperID    lastName     destID   lastName
S12345-0      W-100        Warehouse A  C-22315  Northrop Grumman

这是提供给我的数据,因此使用非姓氏数据填充的lastName列可能只是一个疏忽,所以就这样吧。

1 个答案:

答案 0 :(得分:1)

如果我理解你的问题,你不需要子查询,你只需要将两个表连在一起。客户需要连接两次..一次用于shipperID,一次用于destID以获取相应的lastName。这个查询应该可以解决问题..请参阅工作FIDDLE

SELECT 
    s.shipNumber, 
    s.shipperID, 
    c.lastName AS first_last_name, 
    s.destID, 
    c1.lastName AS second_last_name
FROM shipments s
JOIN customers c ON c.id = s.shipperID
JOIN customers c1 ON c1.id = s.destID