Sql GROUP BY子句或在聚合函数中使用

Sql GROUP BY子句或在聚合函数中使用,sql,postgresql,Sql,Postgresql,我想按发件人\u id进行分组,但出现以下错误: 列“users.first_name”必须出现在GROUP BY子句中,或在聚合函数中使用 闲聊 chatting_id | content | received_id | sender_id 1 | hallo | 4 | 5 2 | whoaa | 4 | 6 3 | wow | 4 | 5 tb_用户

我想按
发件人\u id
进行分组,但出现以下错误:

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

闲聊

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

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

基本上,您需要按照正确的顺序包含在组中被选中的每一列

例如:

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

问题是,您试图使用Group By函数,而不使用count或sum等聚合函数。在本例中,GROUPBY不起作用。但要展示一个简单的示例

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”中使用另一个表,因为如果它们之间没有联接,那么只会有一个包含这两个表的所有字段的表,并且数据之间没有实际的相关性


我建议您学习如何构建数据库模式,这将使您更好地掌握表的设计方式,从而可以编写一流的查询

这是一个极为常见的错误/问题,但我目前找不到一个好的参考答案。要理解错误的含义,请考虑:如果一个特定的
聊天.sender\u id
有多个用户,DBMS应该如何决定哪个用户应该出现在输出行中?(您可能“知道”没有这种情况;DBMS没有。)规则:所有检索到的未包含在聚合函数中的字段(例如,
sum
count”,“average
,等等)必须包含在
GROUP BY
列表中。在postgre中,select字段必须出现在GROUP BY子句中,我知道这很痛苦,但这也是一个很好的实践,正如@a_horse_和_no_name所说的,你没有任何聚合函数,所以为什么不删除group by子句呢?什么逻辑更喜欢“whoaa”而不是“woe”?数据没有出现
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