Postgresql select/join/group 上的错误语法

发布于 2024-10-28 21:21:29 字数 298 浏览 2 评论 0原文

下面的内容对于 Postgresql 来说是不正确的语法吗?

select p.*, SUM(vote) as votes_count 
FROM votes v, posts p 
where p.id = v.`voteable_id` 
  AND v.`voteable_type` = 'Post' 
group by v.voteable_id 
order by votes_count DESC limit 20

我正在本地安装 postgresql,但想尽快解决这个问题:)

谢谢

What about the following is not proper syntax for Postgresql?

select p.*, SUM(vote) as votes_count 
FROM votes v, posts p 
where p.id = v.`voteable_id` 
  AND v.`voteable_type` = 'Post' 
group by v.voteable_id 
order by votes_count DESC limit 20

I am in the process of installing postgresql locally but wanted to get this out sooner :)

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天暗了我发光 2024-11-04 21:21:29

MySQL 对标准 SQL 的解释比 PostgreSQL 宽松得多。您的查询有两个问题:

  1. 反引号是 MySQL 的问题。
  2. 您的 GROUP BY 无效。

第一个问题可以通过简单地删除有问题的引号来修复。第二个需要更多的工作;来自精细手册

当存在 GROUP BY 时,SELECT 列表表达式引用未分组的列(聚合函数内除外)是无效的,因为可能有多个可能为未分组的列返回的值。

这意味着 SELECT 中提到的每一列都必须出现在聚合函数或 GROUP BY 子句中。因此,您必须扩展您的 p.* 并确保所有这些列都在 GROUP BY 中,您最终应该得到类似这样的结果,但真正的列在place of p.column...

select p.id, p.column..., sum(v.vote) as votes_count
from votes v, posts p
where p.id = v.voteable_id
  and v.voteable_type = 'Post'
group by p.id, p.column...
order by votes_count desc
limit 20

从 MySQL 迁移到其他任何东西时,这是一个非常常见的问题。

MySQL is a lot looser in its interpretation of standard SQL than PostgreSQL is. There are two issues with your query:

  1. Backtick quoting is a MySQL thing.
  2. Your GROUP BY is invalid.

The first one can be fixed by simply removing the offending quotes. The second one requires more work; from the fine manual:

When GROUP BY is present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions, since there would be more than one possible value to return for an ungrouped column.

This means that every column mentioned in your SELECT either has to appear in an aggregate function or in the GROUP BY clause. So, you have to expand your p.* and make sure that all those columns are in the GROUP BY, you should end up with something like this but with real columns in place of p.column...:

select p.id, p.column..., sum(v.vote) as votes_count
from votes v, posts p
where p.id = v.voteable_id
  and v.voteable_type = 'Post'
group by p.id, p.column...
order by votes_count desc
limit 20

This is a pretty common problem when moving from MySQL to anything else.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文