起初 - 我是sql新手,对此(mbe typicall)问题感到抱歉。
我有两张桌子:组织表......
id_org org_name
1 Organiz1
2 Organiz2
和组织工作人员表。
id_staff staff_name id_org
1 John 1
2 Jack 1
3 Sally 1
4 Peter 1
5 Andy 2
6 Joe 2
我想要像这样的SQL回答(两行)
1 Organiz1 1 John 2 Jack 3 Sally 4 Peter
2 Organiz2 5 Andy 6 Joe
我想知道员工的每个姓名或身份证名称为staff_1_name(staff_2_name,staff_3_name)和staff_1_id。 我怎么能得到它?
答案 0 :(得分:3)
SELECT o.id_org, o.org_name, GROUP_CONCAT(concat(s.id_staff, ' ', s.staff_name) ORDER BY s.id_staff SEPARATOR ' ')
FROM Organizations o, staff s
WHERE s.id_org = o.id_org
GROUP BY id_org, org_name;
答案 1 :(得分:2)
你很幸运。 MySQL提供了一个名为GROUP_CONCAT()
的便捷函数,您可以使用它来构建结果集:
SELECT o.id_org, o.org_name, GROUP_CONCAT(s.staff_name_id SEPARATOR ' ')
FROM organisations o
JOIN (
SELECT id_staff,
id_org,
CONCAT(id_staff, ' ', staff_name) staff_name_id
FROM staff
) s ON (s.id_org = o.id_org)
GROUP BY o.id_org, o.org_name;
测试用例:
CREATE TABLE organisations (id_org int, org_name varchar(20));
CREATE TABLE staff (id_staff int, staff_name varchar(20), id_org int);
INSERT INTO organisations VALUES (1, 'Organiz1');
INSERT INTO organisations VALUES (2, 'Organiz2');
INSERT INTO staff VALUES (1, 'John', 1);
INSERT INTO staff VALUES (2, 'Jack', 1);
INSERT INTO staff VALUES (3, 'Sally', 1);
INSERT INTO staff VALUES (4, 'Peter', 1);
INSERT INTO staff VALUES (5, 'Andy', 2);
INSERT INTO staff VALUES (6, 'Joe', 2);
结果:
+--------+----------+---------------------------------------------+
| id_org | org_name | GROUP_CONCAT(s.staff_name_id SEPARATOR ' ') |
+--------+----------+---------------------------------------------+
| 1 | Organiz1 | 1 John 2 Jack 3 Sally 4 Peter |
| 2 | Organiz2 | 5 Andy 6 Joe |
+--------+----------+---------------------------------------------+
2 rows in set (0.00 sec)
<强>更新强>
@Micahel's solution也会返回相同的结果。我建议使用该解决方案,因为您可以直接在GROUP_CONCAT()
函数中连接字段,而不是使用派生表:
SELECT o.id_org,
o.org_name,
GROUP_CONCAT(CONCAT(id_staff, ' ', staff_name) SEPARATOR ' ')
FROM organisations o
JOIN staff s ON (s.id_org = o.id_org)
GROUP BY o.id_org, o.org_name;