sql列出表a与表b的关联数据

ehxuflar  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(327)

给定有电话号码(表:电话)的人(表:联系人),
如何编写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
0yg35tkg

0yg35tkg1#

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;

因为postgresql9.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;

相关问题