在mysql中分组两列

时间:2012-03-21 16:03:30

标签: mysql

我有疑问? 我有一张桌子

    sender_user_id  receiver_user_id        
        2               3           
        3               2           
        2               7       
        2               8           
        7               3           
       10               6               
        2               3       

我希望按sender_user_idreceiver_user_id对列进行分组 应将(sender id=2 and receiver_id=3)(sender id=3 and receiver_id=2)归为一列max timestamp

6 个答案:

答案 0 :(得分:2)

这是你在找什么?

SELECT CONCAT(sender_user_id,' ', receiver_user_id ) as newcolumn, max(datestamp)
from temptable
group by CONCAT(sender_user_id,' ', receiver_user_id ) ;

Really crude, quick, SQLFiddle Solution

答案 1 :(得分:1)

不清楚你的意思。你想要像

这样的东西吗?
   group by sender_id, reciever_id
   order by timestamp desc

答案 2 :(得分:1)

试试这个:

select max(timestamp) from yourTable group by sender_user_id, receiver_user_id

答案 3 :(得分:1)

不确定是否可以使用GROUP BY组合这两列来完成此操作。你可以试试UNION

SELECT user1,user2,MAX(timestamp) FROM 
(SELECT
  sender_user_id AS user1,
  receiver_user_id AS user2,
  timestamp
FROM table
) AS table1
UNION DISTINCT
(SELECT 
  receiver_user_id AS user1,
  sender_user_id AS user2,
  timestamp
FROM table) AS table2
GROUP BY user1,user2

答案 4 :(得分:1)

SELECT *, MAX(timestamp) FROM <my_table> GROUP BY sender_user_id, receiver_user_id

答案 5 :(得分:1)

尝试将GROUP BY作为子查询,然后再进行CONCAT

SELECT
    CONCAT(sender_user_id,' ',receiver_user_id) sender_receiver,
    max_datestamp
FROM
(
    SELECT sender_user_id,receiver_user_id, max(datestamp) max_datestamp
    FROM temptable GROUP BY sender_user_id,receiver_user_id
) A; 

确保temptable已正确编入索引

ALTER TABLE temptable ADD INDEX sender_receiver_ndx (sender_user_id,receiver_user_id);