我想写一个mysql语句,它将返回一个表中的结果列表以及另一个表中逗号分隔的字段列表。我想一个例子可能更好地解释它
Table 1
========================
id First_Name Surname
----------------------
1 Joe Bloggs
2 Mike Smith
3 Jane Doe
Table 2
========================
id Person_Id Job_id
---------------------
1 1 1
2 1 2
3 2 2
4 3 3
5 3 4
我想返回一个逗号分隔的job_id列表的人员列表。所以我的结果集是
id First_Name Surname job_id
------------------------------
1 Joe Bloggs 1,2
2 Mike Smith 2
3 Jane Doe 3,4
我猜sql会像
select id, First_Name, Surname, (SELECT job_id FROM Table 2) as job_id from Table 1
但显然这不起作用,因此需要将'(SELECT job_id FROM Table 2)更改为job_id'部分。
希望这是有道理的
由于 约翰
答案 0 :(得分:7)
您可能需要使用GROUP_CONCAT()
功能,如下所示:
SELECT t1.id,
t1.first_name,
t1.last_name,
GROUP_CONCAT(DISTINCT job_id ORDER BY job_id SEPARATOR ',') job_id
FROM Table1 t1
JOIN Table2 t2 ON (t2.Person_id = t1.id)
GROUP BY t1.id;
让我们用您的示例数据进行测试:
CREATE TABLE Table1 (
id int AUTO_INCREMENT PRIMARY KEY,
first_name varchar(50),
last_name varchar(50));
CREATE TABLE Table2 (
id int AUTO_INCREMENT PRIMARY KEY,
person_id int,
job_id int);
INSERT INTO Table1 VALUES (NULL, 'Joe', 'Bloggs');
INSERT INTO Table1 VALUES (NULL, 'Mike', 'Smith');
INSERT INTO Table1 VALUES (NULL, 'Jane', 'Doe');
INSERT INTO Table2 VALUES (NULL, 1, 1);
INSERT INTO Table2 VALUES (NULL, 1, 2);
INSERT INTO Table2 VALUES (NULL, 2, 2);
INSERT INTO Table2 VALUES (NULL, 3, 3);
INSERT INTO Table2 VALUES (NULL, 3, 4);
查询结果:
+----+------------+-----------+--------+
| id | first_name | last_name | job_id |
+----+------------+-----------+--------+
| 1 | Joe | Bloggs | 1,2 |
| 2 | Mike | Smith | 2 |
| 3 | Jane | Doe | 3,4 |
+----+------------+-----------+--------+
请注意,默认情况下,GROUP_CONCAT()
的结果为truncated to the maximum length of 1024。但是,这可以是set to a much larger value。如果需要修改它,请使用SET命令,如下所示:
SET GLOBAL group_concat_max_len = 2048;