简体   繁体   中英

SQL GROUP BY multiple columns?

I have one table and I need to group the entries by two different columns

here is my code

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 

it should be something like group by u1_id AND u2_id

You need to use the original column names, not the aliases. They aren't processed yet (well, in SQL Server they aren't: not sure of 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
...

Edit: MySQL allows aliases in the GROUP BY

So, I suspect the GROUP BY is wrong and ambiguous and need to be like the standard SQL underneath. With or without aliases

Like this question: SQL Query not showing expected result

[end edit]

Note, to make this standard SQL (or run on any other RDBMS), you need to use all the columns in the GROUP BY that are not in an aggregate:

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM