MySQL:带有LEFT JOIN的GROUP_CONCAT

Nic*_*ick 50 mysql sql join aggregate-functions group-concat

我遇到了MySQL的"GROUP_CONCAT"功能问题.我将使用一个简单的帮助台数据库来说明我的问题:

CREATE TABLE Tickets (
 id INTEGER NOT NULL PRIMARY KEY,
 requester_name VARCHAR(255) NOT NULL,
 description TEXT NOT NULL);

CREATE TABLE Solutions (
 id INTEGER NOT NULL PRIMARY KEY,
 ticket_id INTEGER NOT NULL,
 technician_name VARCHAR(255) NOT NULL,
 solution TEXT NOT NULL,
 FOREIGN KEY (ticket_id) REFERENCES Tickets.id);

INSERT INTO Tickets VALUES(1, 'John Doe', 'My computer is not booting.');
INSERT INTO Tickets VALUES(2, 'Jane Doe', 'My browser keeps crashing.');
INSERT INTO Solutions VALUES(1, 1, 'Technician A', 'I tried to solve this but was unable to. I will pass this on to Technician B since he is more experienced than I am.');
INSERT INTO Solutions VALUES(2, 1, 'Technician B', 'I reseated the RAM and that fixed the problem.');
INSERT INTO Solutions VALUES(3, 2, 'Technician A', 'I was unable to figure this out. I will again pass this on to Technician B.');
INSERT INTO Solutions VALUES(4, 2, 'Technician B', 'I re-installed the browser and that fixed the problem.');
Run Code Online (Sandbox Code Playgroud)

请注意,此帮助台数据库有两个票证,每个票证都有两个解决方案条目.我的目标是使用SELECT语句创建数据库中所有票证的列表及其相应的解决方案条目.这是我正在使用的SELECT语句:

SELECT Tickets.*, GROUP_CONCAT(Solutions.solution) AS CombinedSolutions
FROM Tickets
LEFT JOIN Solutions ON Tickets.id = Solutions.ticket_id
ORDER BY Tickets.id;
Run Code Online (Sandbox Code Playgroud)

上面的SELECT语句的问题是它只返回一行:

id: 1
requester_name: John Doe
description: My computer is not booting.
CombinedSolutions: I tried to solve this but was unable to. I will pass this on to Technician B since he is more experienced than I am.,I reseated the RAM and that fixed the problem.,I was unable to figure this out. I will again pass this on to Technician B.,I re-installed the browser and that fixed the problem.
Run Code Online (Sandbox Code Playgroud)

请注意,它将使用故障单1和故障单2的解决方案条目返回故障单1的信息.

我究竟做错了什么?谢谢!

OMG*_*ies 87

使用:

   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
Run Code Online (Sandbox Code Playgroud)

备用:

   SELECT t.*,
          (SELECT GROUP_CONCAT(s.soution)
             FROM SOLUTIONS s 
            WHERE s.ticket_id = t.ticket_id) AS combinedsolutions
     FROM TICKETS t
Run Code Online (Sandbox Code Playgroud)

  • 我认为我的`join`s错了,但我只是错过了一个`GROUP BY`语句,所以`GROUP_CONCAT()`没有聚合值.希望这可以节省一些时间,比如我花了一个小时. (11认同)
  • 但为什么Nick的方法不起作用?它显然没有,但它似乎应该.你能解释一下吗? (4认同)
  • 对于较大的数据集,此处给出的“替代”答案要**多**。 (2认同)

小智 8

您只需要添加一个 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;
Run Code Online (Sandbox Code Playgroud)