子查询中的多个json_object_agg函数返回语法错误

时间:2016-08-27 13:44:39

标签: sql database postgresql

我有两张桌子

CREATE TABLE service (
    id SERIAL PRIMARY KEY,
    image VARCHAR
);

CREATE TABLE service_description (
    id SERIAL PRIMARY KEY,
    service_id INTEGER,
    language_id INTEGER,
    title VARCHAR,
    subtitle VARCHAR,
    col_left TEXT,
    col_right TEXT
);

我正在尝试将第二个表中的最后4列检索为以language_id为键的对象。

以下查询有效(ommited col_left / right以节省空间)

SELECT
 s.*,
 (
   SELECT
     json_object_agg(language_id, title) AS title
   FROM
     service_description sd
 ),
 (
   SELECT
     json_object_agg(language_id, subtitle) AS subtitle
   FROM
     service_description sd
 )

FROM
    service s

虽然我做的时候

SELECT
 s.*,
 (
   SELECT
     json_object_agg(language_id, title) AS title,
     json_object_agg(language_id, subtitle) AS subtitle
   FROM
     service_description sd
 )

FROM
    service s

我得到错误的代码42601 - 语法错误。怎么了?

1 个答案:

答案 0 :(得分:1)

您的查询中的问题是您在sub-query内选择了多个列。试试这样的事情

SELECT * 
FROM   service s 
       CROSS JOIN (SELECT Json_object_agg(language_id, title)    AS title, 
                          Json_object_agg(language_id, subtitle) AS subtitle 
                   FROM   service_description sd) B