column必须出现在GROUP BY子句中或用于聚合函数

时间:2014-10-25 23:20:17

标签: sql ruby-on-rails postgresql

所以我在postgreSQL(以及其他)中提交了提交,用户,故事和视图表,如下所示:

submissions
-----------
user_id
story_id
body

views
-----------
user_id
submissions_id

users
-----------
username

我有一个复杂的SQL查询查找,它返回按用户是否看到它排序的提交(在views表中有user_id和submission_id的条目),然后是它有多少个视图:

    submissions.find_by_sql("select submissions.*,
          count(views.submission_id) as views_count,
          (select count(*) from views
            where views.user_id=#{user_id} and views.submission_id=submissions.id group by id) as counted
          from submissions
          left outer join views on views.submission_id=submissions.id
          where submissions.story_id = #{id}
          group by submissions.id
          order by counted desc, views_count")

我还希望能够获得每次提交的用户名,这应该很简单:只需在users.id = submissions.user_id加入users表,并将users.username添加到选择部分。但是,当我这样做时,我收到错误

column "users.username" must appear in the GROUP BY clause or be used in an aggregate function 

这不应该,因为将用户添加到分组依据会删除具有相同用户的多次提交,并且我不需要聚合函数。

由于我显然必须明确说明这一点,我知道还有很多其他问题要问这个问题,而且没有一个问题能真正回答我的问题。

1 个答案:

答案 0 :(得分:0)

当您拥有group by子句时,在大多数系统中,您都被限制为 仅显示group by语句中select子句中的字段。加上使用count(), sum(),等的任何聚合列

尝试围绕原始查询的其他查询:

select * from 
(
select top 100 percent 
          submissions.id,
          count(views.submission_id) as views_count,
          (select count(*) from views
            where views.user_id=#{user_id} and views.submission_id=submissions.id group by id) as counted
          from submissions
          left outer join views on views.submission_id=submissions.id
          where submissions.story_id = #{id}
          group by submissions.id
          order by counted desc, views_count
) as InnerQuery
left join submissions on submissions.ID = InnerQuery.ID