Mysql SQL从表b中列出表a的关联数据

Mysql SQL从表b中列出表a的关联数据,mysql,sql,postgresql,sqlite,Mysql,Sql,Postgresql,Sqlite,给定人员表:具有电话号码的联系人表:电话 如何编写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 C

给定人员表:具有电话号码的联系人表:电话

如何编写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
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,您可以直接使用string_agg:

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,您可以直接使用string_agg:


SQLite还以某种方式支持GROUP_CONCAT您可能还希望为GROUP_CONCAT使用自定义分隔符:GROUP_CONCATp.phone_number SEPARATOR“”。PostgreSQL 9.0+支持函数string_agg,该函数将array_替换为\u stringarray_agg->SQLite还以某种方式支持GROUP_CONCAT您可能还希望为其使用自定义分隔符GROUP_CONCAT:GROUP_CONCATp.phone_数字分隔符“”。PostgreSQL 9.0+支持函数字符串_agg,该函数将数组_替换为字符串数组_agg->