给定具有电话号码的人(表:联系人)(表:电话),
如何编写SQL查询(Sqlite3,postgres或MySQL)来显示每个人及其所有电话号码?
Table: contacts Table: Phones
id name id phone_number contact_id
1 Ashok 1 (111) 123-1111 1
2 Betty 2 (111) 123-2222 1
3 Charles 3 (111) 123-3333 1
4 (111) 123-4444 1
5 (222) 456-1111 2
6 (222) 456-2222 2
7 (333) 789-1111 3
8 (333) 789-2222 3
9 (333) 789-3333 3
我希望输出为:
Name Phones
Ashok (111) 123-1111 (111) 123-2222 (111) 123-3333 (111) 123-4444
Betty (222) 456-1111 (222) 456-2222
Charles (333) 789-1111 (333) 789-2222 (333) 789-3333
如果我加入:
SELECT c.name, p.phone_number
FROM contacts as c
INNER JOIN phones as p
ON c.id = p.contact_id
ORDER BY c.name
结果不是我想要的:
Name Phone
Ashok (111) 123-1111
Ashok (111) 123-2222
Ashok (111) 123-3333
Ashok (111) 123-4444
Betty (222) 456-1111
Betty (222) 456-2222
Charles (333) 789-1111
Charles (333) 789-2222
Charles (333) 789-3333
答案 0 :(得分:4)
MySQL 和 SQLite 都有GROUP_CONCAT()
函数:
SELECT c.name, GROUP_CONCAT(p.phone_number) AS Phones
FROM contacts AS c
INNER JOIN phones AS p ON c.id = p.contact_id
GROUP BY c.name
ORDER BY c.name;
在 PostgreSQL 中,您可以使用array_to_string()
和array_agg()
函数:
SELECT c.name, array_to_string(array_agg(p.phone_number), ',') AS Phones
FROM contacts AS c
INNER JOIN phones AS p ON c.id = p.contact_id
GROUP BY c.name
ORDER BY c.name;
自 PostgreSQL 9.0以来,您可以直接使用string_agg()
:
SELECT c.name, string_agg(p.phone_number, ',') AS Phones
FROM contacts AS c
INNER JOIN phones AS p ON c.id = p.contact_id
GROUP BY c.name
ORDER BY c.name;