一尘不染

MySQL:如何多次连接同一张表?

mysql

我有两个桌子ticketattr。表ticket具有ticked_id字段和其他几个字段。表attr具有3个字段:

ticket_id - numeric
attr_type - numeric
attr_val - string

attr_type是固定的值枚举。例如,它可以是123

我需要进行查询,其结果将是4列:

ticket_idattr_valattr_type=1attr_valattr_type=2attr_valattr_type=3

如果不存在用于相应值attr_typeattr表然后NULL值应在相应的列中显示。

例:

ticket
    ticket_id: 1

    ticket_id: 2

    ticket_id: 3


attr
    ticket_id: 1
    attr_type: 1
    attr_val: Foo

    ticket_id: 1
    attr_type: 2
    attr_val: Bar

    ticket_id: 1
    attr_type: 3
    attr_val: Egg

    ticket_id: 2
    attr_type: 2
    attr_val: Spam

结果应该是:

ticked_id: 1
attr_val1: Foo
attr_val2: Bar
attr_val3: Egg

ticked_id: 2
attr_val1: NULL
attr_val2: Spam
attr_val3: NULL

ticked_id: 3
attr_val1: NULL
attr_val2: NULL
attr_val3: NULL

我尝试了attr3次左联接表,但无法弄清楚如何排列输出attr_type


阅读 997

收藏
2020-05-17

共1个答案

一尘不染

您需要使用多个LEFT JOINs

SELECT 
    ticket.ticket_id,  
    a1.attr_val AS attr_val1,
    a2.attr_val AS attr_val2,
    a3.attr_val AS attr_val3
FROM ticket
    LEFT JOIN attr a1 ON ticket.ticket_id=a1.ticket_id AND a1.attr_type=1
    LEFT JOIN attr a2 ON ticket.ticket_id=a2.ticket_id AND a2.attr_type=2
    LEFT JOIN attr a3 ON ticket.ticket_id=a3.ticket_id AND a3.attr_type=3

这是一个示例:SQL Fiddle

2020-05-17