Mysql - 由多列组成

时间:2011-08-28 08:42:05

标签: mysql sql

我想生成一个类似线程的视图

在表格中,我有from,to,date和其他一些列

我想将AND分组的行输出到

DB中的示例数据

from,to,date
a,b,somedate
a,c,somedate
b,a,somedate

查询:

SELECT 
    from, to, date 
FROM 
    data 
GROUP BY 
    from, to 
ORDER BY 
    date DESC;

我期望的输出是这样的:(其中from和to组合在一起)

a,b,somedate
a,c,somedate

(b,a,somedate not shows because its in the a,b group) 

但它没有..

一般的想法是“按用户”设置消息视图。 列表按收件人排序,日期(而不是消息)......

1 个答案:

答案 0 :(得分:4)

如果您想为每个(from, to)组合返回一行:

SELECT one, two, MIN(somedate) 
FROM
( SELECT `from` AS one, `to` AS two, somedate 
  FROM data 
  WHERE `from` <= `to`
UNION ALL
  SELECT `to`, `from`, somedate 
  FROM data 
  WHERE `from` > `to`
) AS tmp
GROUP BY one
       , two
ORDER BY one
       , two

或者,如果您想要所有记录:

SELECT one, two, somedate 
FROM
( SELECT `from` AS one, `to` AS two, somedate 
  FROM data 
  WHERE `from` <= `to`
UNION ALL
  SELECT `to`, `from`, somedate 
  FROM data 
  WHERE `from` > `to`
) AS tmp
ORDER BY one
       , two