mysql关联表到多个表

时间:2014-02-12 09:00:50

标签: mysql join

我有这样的表:

      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

bID可以只在tableX

是否有一种简单的方法来检索aID 1的所有值?

1 个答案:

答案 0 :(得分: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