如何选择不同条件的同一列?

时间:2013-07-10 16:08:27

标签: sql-server

我正在尝试从两个表格中选择数据 -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

2 个答案:

答案 0 :(得分:6)

您必须将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

答案 1 :(得分:2)

使用subselect可能更清楚:

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解决方案完全相同的查询计划,但对于发生的事情可能会更清楚一些。