SQL GROUP BY多列

时间:2011-08-07 15:24:21

标签: mysql sql

我有一个表,我需要按两个不同的列对条目进行分组

这是我的代码

SELECT *
    FROM (
        SELECT max(user_msg.id) AS mid, max(user_msg.timestamp) AS tsp, user_msg.text, 
        usr1.id AS u1_id, usr1.nickname AS u1_nickname, usr1.avatar AS u1_avatar, usr1.avatar_art AS u1_avatar_art, 
        usr2.id AS u2_id, usr2.nickname AS u2_nickname, usr2.avatar AS u2_avatar, usr2.avatar_art AS u2_avatar_art,
        COUNT(user_msg.id) AS cnt
        FROM user_msg 
        join user using (client_id)
        LEFT JOIN user AS usr1 ON user_msg.from_id=usr1.id
        LEFT JOIN user AS usr2 ON user_msg.to_id=usr2.id
        WHERE user_msg.to_id = '".$user_id."' AND to_delete='0' OR user_msg.from_id = '".$user_id."' AND to_delete='0'
        group by u1_id, u2_id ORDER by tsp DESC
    ) c 

它应该像u1_id和u2_id

这样的组

请帮助

1 个答案:

答案 0 :(得分:3)

您需要使用原始列名称,而不是别名。它们尚未处理(好吧,在SQL Server中它们不是:不确定MYSQL)。

...
   WHERE user_msg.to_id = '".$user_id."' AND to_delete='0' OR user_msg.from_id = '".$user_id."' AND to_delete='0'
  group by usr1.id, usr2.id
  ORDER by tsp DESC
...

修改:MySQL allows aliases in the GROUP BY

所以,我怀疑GROUP BY是错误的和模棱两可的,需要像下面的标准SQL一样。有或没有别名

喜欢这个问题:SQL Query not showing expected result

[结束编辑]

注意,要制作此标准SQL(或在任何其他RDBMS上运行),您需要使用GROUP BY中不在聚合中的所有列:

    SELECT
       max(user_msg.id) AS mid, 
       max(user_msg.timestamp) AS tsp, 
       user_msg.text, 
       usr1.id AS u1_id, usr1.nickname AS u1_nickname, usr1.avatar AS u1_avatar, usr1.avatar_art AS u1_avatar_art, 
       usr2.id AS u2_id, usr2.nickname AS u2_nickname, usr2.avatar AS u2_avatar, usr2.avatar_art AS u2_avatar_art,
       COUNT(user_msg.id) AS cnt
    FROM user_msg 
    join user using (client_id)
    LEFT JOIN user AS usr1 ON user_msg.from_id=usr1.id
    LEFT JOIN user AS usr2 ON user_msg.to_id=usr2.id
    WHERE user_msg.to_id = '".$user_id."' AND to_delete='0' OR user_msg.from_id = '".$user_id."' AND to_delete='0'
    GROUP BY 
          user_msg.text, usr1.id, usr1.nickname, usr1.avatar, usr2.avatar_art,
          usr2.id, usr2.nickname, usr2.avatar, usr1.avatar_art
    ORDER by tsp DESC