laravel PostgreSQL 分组错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16012818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:42:29  来源:igfitidea点击:

PostgreSQL Grouping error

sqlpostgresqllaravel

提问by user2277033

I got this error when i was executing this query on PostgreSQL:

我在 PostgreSQL 上执行此查询时遇到此错误:

SQLSTATE[42803]: Grouping error: 7 ERROR:  column "posts.title" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT DISTINCT posts.id, posts.* FROM "posts" GROUP BY "pos..

and this is my query:

这是我的查询:

SELECT DISTINCT posts.id, posts.* 
FROM "posts" 
GROUP BY "posts"."id" 
ORDER BY "posts"."id" DESC 
LIMIT 20 OFFSET 0

although it did worked when I was executing it with mysql, so how can i fix this?

虽然当我用 mysql 执行它时它确实有效,那么我该如何解决这个问题?

采纳答案by ArchiFloyd

The problem is, that in PostgreSQL you need to add all the columns you want to have in your select to your group by.

问题是,在 PostgreSQL 中,您需要将选择中的所有列添加到组中。

so your statement should be like

所以你的陈述应该是这样的

SELECT * FROM table GROUP BY column1, column2...

回答by Harshil

Try this.

尝试这个。

SELECT DISTINCT * FROM 
(SELECT ROW_NUMBER() OVER(PARTITION BY  "posts"."id" ORDER BY   "posts"."id") No, posts.*
 FROM "posts"  ) AS T1 WHERE T1.NO = 1
 ORDER BY "id" DESC LIMIT 20 OFFSET 0