【问题标题】:SQL in postgresql/php syntax errorpostgresql/php 中的 SQL 语法错误
【发布时间】:2017-04-17 22:02:22
【问题描述】:

这是我的 sql

$sqltable3=
'SELECT 
"Publications"."Pub_ID", 
"Questions"."Question" 
FROM "Publications" 
LEFT JOIN "Aspect_Pub_join" ON "Publications"."Pub_ID"="Aspect_Pub_join"."Pub_ID" 
LEFT JOIN "Aspect_question_join" ON "Aspect_Pub_join"."Aspect_ID"="Aspect_question_join"."Aspect_ID" 
LEFT JOIN "Questions" ON "Aspect_question_join"."Question_ID"="Questions"."Question_ID" 
Where "Publications"."Pub_ID"=$1 
GROUP BY "Questions"."Question" 
ORDER BY "Publications"."Pub_ID" ASC';

这是错误:

警告:pg_query_params():查询失败:错误:列“Publications.Pub_ID”必须出现在 GROUP BY 子句中或用于聚合函数第 1 行:选择“Publications”。“Pub_ID”,“问题”。 “问题” FROM ... ^ in ...

我在 order by 中使用 Publications.Pub_ID 作为聚合函数,所以我不确定我哪里出错了?相同的查询在 mysql 中运行良好(我知道它不那么挑剔)。

如果我去掉 group by 和 order by 函数,那么 sql 会运行,但显然不会返回所需的结果。

【问题讨论】:

    标签: php sql postgresql


    【解决方案1】:

    需要在 group by 中包含 Publications。

    $sqltable3=
    'SELECT 
    "Publications"."Pub_ID", 
    "Questions"."Question" 
    FROM "Publications" 
    LEFT JOIN "Aspect_Pub_join" ON "Publications"."Pub_ID"="Aspect_Pub_join"."Pub_ID" 
    LEFT JOIN "Aspect_question_join" ON "Aspect_Pub_join"."Aspect_ID"="Aspect_question_join"."Aspect_ID" 
    LEFT JOIN "Questions" ON "Aspect_question_join"."Question_ID"="Questions"."Question_ID" 
    Where "Publications"."Pub_ID"=$1 
    GROUP BY "Questions"."Question", 
    "Publications"."Pub_ID" 
    ORDER BY "Publications"."Pub_ID" ASC';
    

    【讨论】:

      【解决方案2】:

      错误非常清楚,因为它要求在选择列表中添加另一列到您的group by 子句,如下所示。尽管没有任何理由需要 group by,因为您没有使用任何聚合函数

      GROUP BY "Questions"."Question" , "Publications"."Pub_ID"
      

      【讨论】:

        猜你喜欢
        • 2016-10-23
        • 2018-12-16
        • 1970-01-01
        • 2013-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多