MySQL左外连接多个表

时间:2015-01-15 05:27:27

标签: mysql sql left-join inner-join where

表:书签

  bid      bname    tagid1      tagid2      tagid3
--------------------------------------------------------------------
   1      bookmark1  1001        1002        1003
   2      bookmark2  1002                    1005
   3      bookmark3              1003        1003
   4      bookmark4                          1003
   5      bookmark5  1001                
   6      bookmark5  1002                    1003

表:标记

  tagid       tagname  
--------------------------
   1001        Java  
   1002        PHP
   1003        Ruby  
   1004        Node.js
   1005        Go  

我期望获得的结果是:

  bid      bname    tagName1    tagName2    tagName3
--------------------------------------------------------------------
   1      bookmark1  Java        PHP         Ruby
   2      bookmark2  PHP                     Go
   3      bookmark3              Ruby        Ruby
   4      bookmark4                          Ruby
   5      bookmark5  Java                
   6      bookmark5  PHP                     Ruby

我怎么能得到这个?

1 个答案:

答案 0 :(得分:5)

您需要多次加入同一个表。您需要每个表的名称别名来区分它们

select b.id, b.bname,
       t1.name as tagName1,
       t2.name as tagName2,
       t3.name as tagName3
from bookmark b
left join tag t1 on t1.tagid = b.tagid1
left join tag t2 on t2.tagid = b.tagid2
left join tag t3 on t3.tagid = b.tagid3

顺便说一句,您应该考虑通过添加另一个用于书签标签映射的表来更改您的表格设计。然后,您可以为每个书签添加任意数量的标签。