簡體   English   中英

從MySQL移動后查詢中的PostgreSQL分組錯誤

[英]PostgreSQL grouping error in a query after moving from MySQL

我已經從MySQL遷移到PostgreSQL,但是遇到了奇怪的問題。 我的查詢在MySQL中運行完美。

SELECT MIN("events"."schedule") AS schedule 
FROM "events"  
WHERE ("events"."state" IN (1)) AND ("events"."schedule" >= '2014-07-01') 
GROUP BY EXTRACT(YEAR FROM "events"."schedule"), 
EXTRACT(MONTH FROM "events"."schedule")  
ORDER BY "events"."schedule" DESC

PostgreSQL給我這個錯誤:

ERROR:  column "events.schedule" must appear in the GROUP BY clause or be used in an aggregate function
LINE 6: ORDER BY "events"."schedule" DESC
             ^

********** Error **********

ERROR: column "events.schedule" must appear in the GROUP BY clause or be used in an aggregate function
SQL state: 42803
Character: 238

當我同時按兩列對數據進行分組時,應如何重寫此查詢以在GROUP BY子句中包含“ events.schedule”?

如果要按結果列(分鍾(時間表))排序,則可以使用以下命令:

SELECT MIN("events"."schedule") AS schedule
  FROM "events"
 WHERE "events"."state" IN (1)
   AND "events"."schedule" >= '2014-07-01'
 GROUP BY EXTRACT(YEAR FROM "events"."schedule"),
          EXTRACT(MONTH FROM "events"."schedule")
 ORDER BY 1 desc

出現錯誤的原因是因為您嘗試按Schedule列本身進行排序,而不是匯總的min(schedule)

您還可以簡化很多:

SELECT MIN(schedule) AS schedule 
FROM   events  
WHERE  state = 1
AND    schedule >= '2014-07-01'
GROUP  BY date_trunc('month', schedule)
ORDER  BY 1 DESC;

特別是,將兩個EXTRACT調用替換為單個date_trunc() 便宜點

您最初的查詢實際上沒有任何意義,因此PostgreSQL拒絕它是正確的。 我不確定MySQL為什么接受它或它實際上在執行哪種排序。

如果您的目標是根據輸出schedule列進行訂購,則可以直接引用SELECT別名(而不是events.schedule

SELECT MIN("events"."schedule") AS schedule 
FROM "events"  
WHERE ("events"."state" IN (1)) AND ("events"."schedule" >= '2014-07-01') 
GROUP BY EXTRACT(YEAR FROM "events"."schedule"), 
EXTRACT(MONTH FROM "events"."schedule")
ORDER BY schedule DESC

否則,您可能需要通過提供一些示例數據來闡明您的問題,以表明您希望如何對結果進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM