【问题标题】:GROUP BY clause or be used in an aggregate functionGROUP BY 子句或在聚合函数中使用
【发布时间】:2018-05-18 20:39:46
【问题描述】:

我想按sender_id 分组,但出现以下错误:

列“users.first_name”必须出现在 GROUP BY 子句中或用于聚合函数中

SELECT users.first_name, users.last_name, users.avatar_url, users.age, chatting.content, chatting.sender_id, chatting.received_id, chatting.created_at as created_at_chatting
FROM users, chatting 
WHERE chatting.received_id = users.id 
  AND received_id='4' 
GROUP BY chatting.sender_id

tb_chatting

chatting_id | content | received_id | sender_id 
1           | hallo   | 4           | 5
2           | whoaa   | 4           | 6
3           | wow     | 4           | 5

tb_users

user_id | first_name  | last_name | age | avatar_url 
5       | dicky       | perdian   | 12  | httpxxxxxxx
6       | ferda       | est       | 13  | httpsxxxxxx

预期输出:

avatar_url | first_name | last_name | content 
httpxxxxxxx| dicky      | perdian   | hallo 
httpsxxxxxx| ferda      | est       | whoaa

【问题讨论】:

  • 一些示例数据在这里会有所帮助。
  • 这是一个非常常见的错误/问题,但我现在找不到很好的参考答案。要了解错误的含义,请考虑:如果特定chatting.sender_id 有多个用户,DBMS 应如何决定应在输出行中出现哪个用户? (您可能“知道”没有这种情况;DBMS 没有。)
  • RULE:所有未包含在聚合函数中的检索字段(例如sumcount', 'average 等)必须包含在GROUP BY 列表中。
  • 在 postgre 中,选择字段必须出现在 group by 子句中,我知道这很痛苦,但这也是一种好习惯,正如@a_horse_with_no_name 所说,你没有任何聚合函数,所以你为什么不只需删除 group by 子句?
  • 喜欢“whoaa”而不是“woe”的逻辑是什么?

标签: sql postgresql


【解决方案1】:

问题是您正在尝试使用 Group By 函数,而没有像 count 或 sum 这样的聚合函数。在这种情况下,Group By 不起作用。但是要显示一个简单的示例,就像

select users.first_name, users.last_name, users.avatar_url, users.age,
count(chatting.content)`--If that field contains messages count is good enough
FROM users
  join chatting c on c.senderid = users.id -- if it exists
WHERE chatting.received_id = users.id AND received_id='4'
GROUP BY users.first_name, users.last_name, users.avatar_url, users.age

另外,我建议不要在“from”中使用另一个表,因为如果它们之间没有连接,那么你只会有一个包含这两个表的所有字段的表,并且数据之间没有真正的关联。

我建议您学习如何构建数据库架构,这将使您更好地了解表的设计方式,以便您编写一流的查询!

【讨论】:

    【解决方案2】:

    基本上,您需要以正确的顺序包含在您的组中选择的每一列。

    例如:

    SELECT users.first_name, 
           users.last_name, 
           users.avatar_url, 
           users.age, 
           chatting.content, 
           chatting.sender_id, 
           chatting.received_id, 
           chatting.created_at as created_at_chatting
    FROM users, chatting 
    WHERE chatting.received_id = users.id 
      AND received_id='4' 
    GROUP BY 
           chatting.sender_id,
           users.first_name, 
           users.last_name, 
           users.avatar_url, 
           users.age, 
           chatting.content, 
           chatting.received_id, 
           chatting.created_at
    

    【讨论】:

    • 数据不出现
    • 它对我有用,谢谢 ;)
    猜你喜欢
    • 2013-08-31
    • 2012-04-27
    • 2012-12-07
    • 2013-07-31
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多