MySQL 左外连接多个表

MySQL left outer join multiple tables

Table: 书签

  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

Table: 标签

  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

我怎么能得到这个?

您需要多次加入同一个 table。每个人都需要一个 table 别名来区分它们

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

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