0

我有一张“汽车”表和一张“人”表。一个人驾驶许多汽车,而汽车可以由许多人驾驶,所以我有另一个表“Person_Car”,每行都有两个 id。

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

我怎样才能获得所有驾驶汽车的人的列表(连接汽车名称),如下所示:

("John", "Car 1, Car 2, Car 3")
("Kate", "Car 2, Car 4, Car 5")
4

2 回答 2

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
于 2016-03-10T21:07:03.100 回答
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;
于 2016-03-10T21:21:05.457 回答