MySQL: How do I join same table multiple times?

后端 未结 3 535
刺人心
刺人心 2020-11-29 08:08

I have two tables ticket and attr. Table ticket has ticked_id field and several other fields. Table attr has

相关标签:
3条回答
  • 2020-11-29 08:27

    While you can use aliased left joins, in this case you could also use a combination of grouping and conditional expressions:

    select t.ticket_id,
           max(case when a.attr_type=1 then a.attr_val end) attr_val1,
           max(case when a.attr_type=2 then a.attr_val end) attr_val2,
           max(case when a.attr_type=3 then a.attr_val end) attr_val3
    from ticket t
    left join attr a on t.ticket_id = a.ticket_id
    group by t.ticket_id
    
    0 讨论(0)
  • 2020-11-29 08:36

    You need to use multiple 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
    

    Here is an example: SQL Fiddle.

    0 讨论(0)
  • 2020-11-29 08:41

    You use table aliases

    eg:

    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 (select * from attr where attr_type=1) a1 on ticket.ticket_id=a1.ticket_id
        left join (select * from attr where attr_type=2) a2 on ticket.ticket_id=a2.ticket_id
        left join (select * from attr where attr_type=3) a3 on ticket.ticket_id=a3.ticket_id
    
    0 讨论(0)
提交回复
热议问题