MySQL: GROUP_CONCAT with LEFT JOIN

前端 未结 3 1742
南笙
南笙 2020-11-29 21:06

I\'m experiencing a problem with MySQL\'s \"GROUP_CONCAT\" function. I will illustrate my problem using a simple help desk database:

CREATE TABLE Tickets (
          


        
相关标签:
3条回答
  • 2020-11-29 21:37

    You just need to add a GROUP_BY :

    SELECT Tickets.*, GROUP_CONCAT(Solutions.solution) AS CombinedSolutions FROM Tickets 
    LEFT JOIN Solutions ON Tickets.id = Solutions.ticket_id 
    GROUP_BY Tickets.id 
    ORDER BY Tickets.id;
    
    0 讨论(0)
  • 2020-11-29 21:38

    Use:

       SELECT t.*,
              x.combinedsolutions
         FROM TICKETS t
    LEFT JOIN (SELECT s.ticket_id,
                      GROUP_CONCAT(s.soution) AS combinedsolutions
                 FROM SOLUTIONS s 
             GROUP BY s.ticket_id) x ON x.ticket_id = t.ticket_id
    

    Alternate:

       SELECT t.*,
              (SELECT GROUP_CONCAT(s.soution)
                 FROM SOLUTIONS s 
                WHERE s.ticket_id = t.ticket_id) AS combinedsolutions
         FROM TICKETS t
    
    0 讨论(0)
  • 2020-11-29 21:49

    I think @Dylan Valade's comment is the simplest answer so I'm posting it as another answer: simply adding a GROUP BY Tickets.id to the OP's SELECT should fix the issue. It fixed my own issue.

    However, for databases that are not small the accepted answer, especially if there are any predicates on Tickets.id appears to not involve a total table scan and so while the previous paragraph returns the correct results it appears to be much less efficient in my case.

    0 讨论(0)
提交回复
热议问题