2016-12-24 19 views
2

我有一个表,如文本消息,其中包含from,tomessagetime列(等等)。我试图要求两个数字(fromto之间的最近记录,而不考虑方向MySQL:按两列分组而不考虑订单

下面是表的一个例子:

+--------------+-----------------+--------------------+--------------+ 
| from   | to    | message   | time   | 
+--------------+-----------------+--------------------+--------------+ 
| 555-1234  | 555-9876  | I'll be there.  | 06:00  | 
| 555-9876  | 555-5555  | message3   | 05:30  | 
| 555-9876  | 555-1234  | Bring beer   | 05:00  | 
| 555-9876  | 555-1234  | My place at 8pm | 04:00  | 
| 555-9876  | 555-5555  | message2   | 03:45  | 
| 555-5555  | 555-9876  | message1   | 03:30  | 
| 555-9876  | 555-1234  | Are you coming? | 03:00  | 
| 555-1234  | 555-9876  | Yeah, what's up? | 02:00  | 
| 555-9876  | 555-1234  | Are you there?  | 01:00  | 
+--------------+-----------------+--------------------+--------------+ 

我想从这个例子中得到的只是以下记录:

+--------------+-----------------+--------------------+--------------+ 
| from   | to    | message   | time   | 
+--------------+-----------------+--------------------+--------------+ 
| 555-1234  | 555-9876  | I'll be there.  | 06:00  | 
| 555-9876  | 555-5555  | message3   | 05:30  | 
+--------------+-----------------+--------------------+--------------+ 

我怎么问这些?

回答

0
SELECT t1.* 
FROM yourTable t1 
INNER JOIN 
(
    SELECT LEAST(`from`, `to`) AS `from`, 
      GREATEST(`from`, `to`) AS `to`, 
      MAX(`time`) AS `max_time` 
    FROM yourTable 
    GROUP BY LEAST(`from`, `to`), 
      GREATEST(`from`, `to`) 
) t2 
    ON LEAST(t1.`from`, t1.`to`) = t2.`from` AND 
     GREATEST(t1.`from`, t1.`to`) = t2.`to` AND 
     t1.`time` = t2.`max_time` 

顺便说一下,命名您的列from,这是一个MySQL关键字是什么原因?请使用其他名称。

+0

Downvoter:请留下反馈。 –

+0

内部连接不会仅返回与两个方向中的记录的对话吗?我意识到我给出的例子只有这些,但用例并不一定。另外:我使用'from'而不是使用我的REAL代码,它实际上是两个表格,一个出现两次,以简化示例。我更好地请求一个更简单的问题,并强制使用转义字符(')的有效答案而不是贬低用例。 – Bing

+0

@Bing不,“INNER JOIN”与此无关。我会建议你尝试我的查询,然后给出反馈。 –

0

您coynd使用,最大子查询和元组

select * from my_table 
where (from, to, time) in (select from, to, max(time) 
          from my_table 
          group by from, to) 
+0

这也可能有问题,因为它将把'from,to'视为与'to,from'不同的值来表示同一对值。 –

+0

@TimBiegeleisen谢谢..我知道..但我主要是一个建议如何使用元组,子查询和组获得这些值..(我不知道OP的真正需要) – scaisEdge

0
select * 
from messages m1 
where time = greatest((
    select max(time) 
    from messages m2 
    where m2.from = m1.from 
     and m2.to = m1.to 
),(
    select max(time) 
    from messages m2 
    where m2.from = m1.to 
     and m2.to = m1.from 
)) 

http://rextester.com/RDTZAK70241