2014-02-12 67 views
0

我的表是這樣的:MySQL的關聯表到多個表

 map   table1   table2   table3 
| aID | bID | | bid | val |  | bid | val | | bid | val | 
------------- -------------  ------------- ------------- 
| 1 | 1 | | 1 | 20 |  | 3 | 10 | | 4 | 15 | 
------------- -------------  ------------- ------------- 
| 1 | 2 | | 1 | 22 |  | 3 | 23 | | 4 | 25 | 
------------- -------------  ------------- ------------- 
| 1 | 3 | | 2 | 15 |  | 3 | 14 | | 4 | 11 | 
------------- -------------  ------------- ------------- 
| 2 | 3 | | 2 | 23 |  | 5 | 32 | | 2 | 3 | 
------------- 
| 2 | 4 | 
------------- 

試過這樣:

SELECT val, bid 
    FROM map m 
    RIGHT JOIN table1 t 
    ON m.bID =t.bid 
    RIGHT JOIN table2 tt 
    ON m.bID =tt.bid 
    RIGHT JOIN table3 ttt 
    ON m.bID =ttt.bid 
    WHERE aID = 1 

出價只是在TableX的一個

是有一個簡單的如何檢索aID 1的所有值?

+0

使用左連接,而不是右連接 – PravinS

回答

1

嘗試此查詢

SELECT val, bid 
FROM map m 
LEFT JOIN table1 t 
    ON m.bID =t.bid 
LEFT JOIN table2 tt 
    ON m.bID =tt.bid 
LEFT JOIN table3 ttt 
    ON m.bID =ttt.bid 
WHERE aID = 1 

確定,基於對你的意見我編輯自己的帖子,試試這個

SELECT val, bid 
FROM map m 
LEFT JOIN table1 t 
    ON m.bID =t.bid 
WHERE aID = 1 
UNION 
SELECT val, bid 
FROM map m 
LEFT JOIN table2 tt 
    ON m.bID =tt.bid 
WHERE aID = 1 
UNION 
SELECT val, bid 
FROM map m 
LEFT JOIN table3 ttt 
    ON m.bID =ttt.bid 
WHERE aID = 1 
+0

這是不行的那麼容易,它說'#1052列'val'在字段列表中是不明確的,那麼我必須單獨選擇每個'val't.val','tt.val' ...並且由於我有很多字段,它將變得複雜。 – InTry

+0

好的,檢查已編輯的答案 – miltos

+0

這是行得通,謝謝...在tableX上加入一個表的情況下,它必須針對每個tableX(table1,table2)單獨完成? – InTry