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,但我们只需要其中一个具有最新创建时间的行。

感谢您的任何建议!

4

2 回答 2

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 的最大创建值关联的值。

于 2010-06-21T17:19:45.490 回答
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
于 2010-06-21T17:20:15.447 回答