我想一个查询,输出1行的Id左表和连接表的说明。
架构:
person
---------
id (int)
role
-------------
id (int)
description (varchar(100))
personrole
-------------
personid (int)
roleid (int)
实施例的数据:
person
------------
id
1
2
role
------------
id description
1 user
2 admininstrator
3 tester
personrole
-------------
personid roleid
1 1
2 1
2 2
2 3
所以,我想输出是:
PersonId Roles
1 user
2 user;administrator;tester
SELECT
p.ID PersonID,
STUFF(
(SELECT ';' + b.description
FROM personrole a
INNER JOIN role b
ON a.roleid = b.id
WHERE a.personid = p.id
FOR XML PATH (''))
, 1, 1, '') AS DescriptionList
FROM person AS p
GROUP BY p.ID
OUTPUT
╔══════════╦════════════════════════════╗
║ PERSONID ║ DESCRIPTIONLIST ║
╠══════════╬════════════════════════════╣
║ 1 ║ user ║
║ 2 ║ user;admininstrator;tester ║
╚══════════╩════════════════════════════╝
另一SQL例如:使用GROUP_CONCAT在单个表来组一个小镇的每名客户。
脚本SQLite的:
表:
CREATE TABLE IF NOT EXISTS 'user'(
prenom STRING,
age INTEGER,
ville STRING);
数据:
INSERT INTO 'user' ('prenom', 'age', 'ville') VALUES
('Anthony', 20, 'Toulouse'),
('Clarisse', 18, 'Paris'),
('Madeleine', 58, 'Paris'),
('Jacques', 45, 'Toulouse'),
('Henry', 26, 'Toulouse'),
('Lili', 14, 'Nice'),
('Victoire', 38, 'Paris');
正常选择:
SELECT * FROM 'user';
OUTPUT:
prenom age ville
-------- -- ---------
Anthony 20 Toulouse
Clarisse 18 Paris
Madeleine 58 Paris
Jacques 45 Toulouse
Henry 26 Toulouse
Lili 14 Nice
Victoire 38 Paris
所有姓组由城市:
SELECT ville, GROUP_CONCAT(prenom, ',') FROM user GROUP BY ville;
OUTPUT:
ville liste
-------- ---------
Nice Lili
Paris Clarisse,Madeleine,Victoire
Toulouse Anthony,Jacques,Henry
SQL服务器(从2017)支持开箱即用的功能STRING_AGG
select p.id, STRING_AGG(pr.description, ',') as roles
from person p
inner join personrole pr ON p.id = pr.personid
inner join roles r ON r.id = pr.roleid
group by p.id