【发布时间】: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:所有未包含在聚合函数中的检索字段(例如
sum、count', 'average等)必须包含在GROUP BY列表中。 -
在 postgre 中,选择字段必须出现在 group by 子句中,我知道这很痛苦,但这也是一种好习惯,正如@a_horse_with_no_name 所说,你没有任何聚合函数,所以你为什么不只需删除 group by 子句?
-
喜欢“whoaa”而不是“woe”的逻辑是什么?
标签: sql postgresql