PostgreSQL:获得一个拥有所有关系的实体

时间:2016-03-10 20:31:11

标签: sql postgresql join inner-join array-agg

我有一张桌子"汽车"和一个表"人"。一个人驾驶许多汽车,一辆汽车可以由许多人驾驶,所以我有另一张桌子" Person_Car"其中每行都有id。

ISeq

如何获得所有驾驶汽车的人员列表(汽车名称连接),如下所示:

Car(id, name)
Person(id, name)
Person_Car(car_id, person_id)

2 个答案:

答案 0 :(得分:0)

示例在这里:http://sqlfiddle.com/#!15/ba949/1

测试数据:

Create table Car(id int, name text);
Create table Person(id int, name text);
Create table Person_Car(car_id int, person_id int);

INSERT INTO Car VALUES (1, 'Car 1'),
  (2, 'Car 2'),
  (3, 'Car 3'),
  (4, 'Car 4'),
  (5, 'Car 5');

INSERT INTO Person VALUES(1, 'John'), (2, 'Kate');

INSERT INTO Person_Car VALUES (1,1), (2,1), (3,1), (2,2), (4,2), (5,2);

您想要的代码:

SELECT p.name, array_to_string(array_agg(c.name), ',') FROM Person p 
    INNER JOIN Person_Car pc ON p.id=pc.person_id 
    INNER JOIN Car c ON c.id=pc.car_id 
    GROUP by p.name

输出:

John    Car 1,Car 2,Car 3
Kate    Car 2,Car 4,Car 5

答案 1 :(得分:0)

以防您想避开GROUP BY

选项1

WITH forienKeyTable AS
(
  SELECT pc.person_id, c.name 
  FROM Car c 
  JOIN Person_Car pc ON pc.car_id = c.id
)
SELECT p.name
    , array_to_string
        (ARRAY(
            SELECT fkt.name 
            FROM forienKeyTable fkt
            WHERE fkt.person_id = p.id
        )::text[], ','::text, 'empty'::text)
FROM Person p;

选项2

SELECT p.name
    , array_to_string
        (ARRAY(
            SELECT c.name 
            FROM Car c 
            JOIN Person_Car pc ON pc.car_id = c.id
            WHERE pc.person_id = p.id
        )::text[], ','::text, 'empty'::text)
FROM Person p;