2016-12-24 21 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