PostgreSQL分组错误

时间:2013-04-15 10:21:50

标签: sql postgresql laravel

我在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..

这是我的疑问:

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

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

2 个答案:

答案 0 :(得分:3)

问题是,在PostgreSQL中,你需要将你想要的所有列添加到你的组中。

所以你的陈述应该是

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

答案 1 :(得分:-1)

试试这个。

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