我想按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

肺结核聊天
chatting_id | content | received_id | sender_id
1           | hallo   | 4           | 5
2           | whoaa   | 4           | 6
3           | wow     | 4           | 5

结核病患者
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

关于sql - GROUP BY子句或在聚合函数中使用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50373747/

10-12 15:38