2013-07-10 79 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