我在使用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.');
注意这个帮助台数据库有两个工单,每个工单都有两个解决方案条目。我的目标是使用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;
上述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.
请注意,它返回票1的信息,并显示票1和票2的解决方案条目。
我做错了什么?谢谢!
join
操作有问题,但实际上我只是漏了一个GROUP BY
语句,因此GROUP_CONCAT()
函数没有聚合数值。希望这能节省其他人的时间,就像我花费一小时才明白一样。 - Dylan Valade