使用子查询

时间:2016-06-17 10:48:09

标签: sql json postgresql subquery

当我选择列并且使用json_build_object时,PostgreSQL 9.5出现问题,我在GROUP BY子句中出错。

我有三张桌子:

Table contact

  Colonne  |           Type           
-----------+--------------------------
 id        | integer                  
 lastname  | character varying(255)   
 firstname | character varying(255)   

此表是联系人表

Table companie

  Colonne  |           Type           
-----------+--------------------------
 id        | integer                  
 name      | character varying(255)   

此表是公司表

Table companie_contact

  Colonne  |           Type           
-----------+--------------------------
 id        | integer                  
 id_c      | integer                  
 id_cm     | integer                  

此表是与公司链接联系人的多对多关系,反之亦然。

当我执行此查询时,所有工作

SELECT co.id,
json_build_object(
  'lastname', co.lastname,
  'firstname', co.firstname) AS contact,
array_agg(c.name) AS companies
FROM companie AS c
INNER JOIN companie_contact AS vs
ON c.id = vs.id_cm
INNER JOIN contact AS co
ON co.id = vs.id_c
GROUP BY co.id;

我得到了

 id |                    contact                   |  companies
----+----------------------------------------------+-------------
  1 | {"lastname" : "some", "firstname" : "one"}   | {A,B,D,E,F}
  4 | {"lastname" : "some", "firstname" : "two"}   | {A}
  2 | {"lastname" : "some", "firstname" : "three"} | {B}

但是当我用View或子查询替换contact和companie时 如下所示

-- Imagine that the views are more complex than that
CREATE VIEW view_contact AS SELECT * FROM contact

CREATE VIEW view_companie AS SELECT * FROM companie

SELECT co.id,
json_build_object(
  'lastname', co.lastname,
  'firstname', co.firstname) AS contact,
array_agg(c.name) AS companies
FROM view_companie AS c
INNER JOIN companie_contact AS vs
ON c.id = vs.id_cm
INNER JOIN view_contact AS co
ON co.id = vs.id_c
GROUP BY co.id;

我收到了这个错误

ERROR:  column "co.lastname" must appear in the GROUP BY clause or be used in an aggregate function 
LINE 1: SELECT co.id,json_build_object('lastname', co.lastname, 'fi...

我不知道为什么会出现这个错误,我在网上找不到解决我特定问题的方法

感谢您的帮助

PS:对不起我的英语我是法国人

1 个答案:

答案 0 :(得分:0)

您可以尝试:

SELECT co.id,
json_build_object(
  'lastname', co.lastname,
  'firstname', co.firstname) AS contact,
array_agg(c.name) AS companies
FROM companie AS c
INNER JOIN companie_contact AS vs
ON c.id = vs.id_cm
INNER JOIN contact AS co
ON co.id = vs.id_c
GROUP BY co.id, co.firstname, co.lastname,c.name ;