我需要一个select命令来执行以下操作:
我有一张这样的表
TIMESTAMP | ID | col1 | col2 | ...
t | 23 | AAA | BBB | ...
t | 23 | BBB | AAA | ...
t | 59 | asf | 567 | ...
t | 02 | XXX | ZZZ | ...
t | 02 | YYY | XXX | ...
t-1 | 23 | AAA | BBB | ...
t-1 | 23 | BBB | AAA | ...
t-1 | 59 | asf | 567 | ...
t-1 | 02 | XXX | ZZZ | ...
t-1 | 02 | YYY | XXX | ...
t-2 | .. | ... | ... | ...
t-2 | .. | ... | ... | ...
每次有时会有2行具有相同的ID。现在我想选择最新的(只有timestamp = t),它们在两个特定列(此处为col1,col2)中也具有相同的直径相邻条目,就像示例中的前两行一样。通过类比,这些具有相同的ID但不同的条目(见最后两行)。
作为示例的结果,我希望有两个选择:
TIMESTAMP | ID | col1 | col2 | ...
t | 23 | AAA | BBB | ...
t | 23 | BBB | AAA | ...
和
TIMESTAMP | ID | col1 | col2 | ...
t | 02 | XXX | ZZZ | ...
t | 02 | YYY | XXX | ...
我知道它应该适用于此
SELECT a.id, a.col1, a.col2
FROM tbl AS a
JOIN tbl AS b ON
( a.id=b.id
AND (a.col1 = b.col2 OR a.col2 = b.col1)
AND (a.col1 != b.col1 AND a.col2 != b.col2)
)
但我不知道如何只选择最新的条目...
答案 0 :(得分:0)
到目前为止,您的查询中需要DISTINCT
以及最新的时间戳谓词:
select distinct ta.*
from tbl ta
JOIN tbl AS tb ON
( ta.id=tb.id
AND (ta.col1 = tb.col2 OR ta.col2 = tb.col1)
AND (ta.col1 != tb.col1 AND ta.col2 != tb.col2)
)
inner join (
SELECT a.id,max(a.`timestamp`) as maxTimestamp
FROM tbl AS a
JOIN tbl AS b ON
( a.id=b.id
AND (a.col1 = b.col2 OR a.col2 = b.col1)
AND (a.col1 != b.col1 AND a.col2 != b.col2)
)
GROUP by a.id
) b on b.id = ta.id and b.maxTimestamp = ta.`timestamp`;