2010-06-21 17 views
0

我有以下結構的表中選擇不同的值:從兩列

itemId | direction | uid | created 
133   0  17 1268497139 
432   1  140 1268497423 
133   0  17 1268498130 
133   1  17 1268501451 

我需要爲兩列中選擇不同的值 - itemIddirection,所以輸出會是這樣:

itemId | direction | uid | created 
432   1  140 1268497423 
133   0  17 1268498130 
133   1  17 1268501451 

在原始表格中,我們有兩行itemId - 133和direction - 0,但我們只需要其中一行具有最新創建時間。

謝謝你的任何建議!

回答

1

用途:

SELECT t.itemid, 
     t.direction, 
     t.uid, 
     t.created 
    FROM TABLE t 
    JOIN (SELECT a.itemid, 
       MAX(a.created) AS max_created 
      FROM TABLE a 
     GROUP BY a.itemid) b ON b.itemid = t.itemid 
          AND b.max_created = t.created 

你必須使用集合(IE:MAX),以獲得每itemid的最大創造價值,並加入該到表的一個不變的副本,以獲得與關聯的值每個itemid的最大創建值。

1
select t1.itemid, t1.direction, t1.uid, t1.created 
from (select t2.itemid, t2.direction, t2.created as maxdate 
     from tbl t2 
     group by itemid, direction) x 
inner join tbl t1 
    on t1.itemid = x.itemid 
    and t1.direction = x.direction 
    and t1.created = x.maxdate