2013-07-10 39 views
0

我想从两个表中选择数据。
- 仓库有两列:warehouseId,warehouseName
- 交通有三列:转运,warehouseId1,warehouseId2
我想从两个表中选择并从warehouseId1和warehouseId2 表A中得到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

您必须添加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 
+0

它的作品,非常感谢! – Victor

1

这可能是更清晰使用子查询:

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

+0

感谢您的帮助! – Victor