3

我正在尝试从两个表中选择数据。
-warehouse 有两列:warehouseId、warehouseName
-transportation 有三列:transporter、warehouseId1、warehouseId2
我想从两个表中选择并从表 A 中为warehouseId1 和warehouseId2 获取warehouseName 这是我的代码,但它不起作用。

select a.transporter, b.warehouseName as warehouse1, b.warehouseName as warehouse2
from transportation a, warehouse b
where a.warehouseId1 = b.warehouseId and a.warehouseId2 = b.warehouseId
4

2 回答 2

7

您必须添加warehouse两次FROM(只需记住为它们使用两个不同的别名):

SELECT
    a.transporter,
    b1.warehouseName as warehouse1,
    b2.warehouseName as warehouse2
FROM
    transportation a,
    warehouse b1,
    warehouse b2
WHERE
        a.warehouseId1 = b1.warehouseId
    AND
        a.warehouseId2 = b2.warehouseId

或使用JOIN语法:

SELECT
    a.transporter,
    b1.warehouseName AS warehouse1,
    b2.warehouseName AS warehouse2
FROM
    transportation a
JOIN
    warehouse b1 ON a.warehouseId1 = b1.warehouseId
JOIN
    warehouse b2 ON a.warehouseId2 = b2.warehouseId
于 2013-07-10T16:10:07.577 回答
2

使用子选择可能更清楚:

SELECT 
    a.transporter,
    (SELECT warehouseName FROM warehouse WHERE warehouseId=a.warehouseId1) AS warehouse1,
    (SELECT warehouseName FROM warehouse WHERE warehouseId=a.warehouseId2) AS warehouse2
FROM
    transportation a

这通常会使用与 MarcinJuraszek 的解决方案完全相同的查询计划,但对于正在发生的事情可能会更清楚一些。

于 2013-07-10T16:19:48.907 回答