0

我有一个非常相似的问题: Finding the 'earliest'composite primary key

但是,我使用的是 MySQL 5.0.77,只需要获取最新的记录。我的表 TABLE_1 如下所示:

OID     PROP_TYPE     EFFECTIVE_DATE        PROP_VALUE
-----   ----------    -------------------   ----------
00123   NA010         2003-05-30 15:52:15   JAMES
00123   NA010         2004-02-30 10:12:18   FRED
00123   NA011         2003-05-30 08:25:41   WILLIAMS
00123   NA011         2006-01-15 22:12:38   DANIELS
00123   NA012         2003-05-30 08:25:41   (704) 242-2124

有一个 OID、PROP_TYPE 和 EFFECTIVE_DATE 的复合键,所以我正在寻找一个检索以下内容的 select 语句:

OID       PROP_TYPE    EFFECTIVE_DATE       PROP_VALUE
-----     ---------    -------------------   -------
00123     NA010        2004-02-30 10:12:18   FRED
00123     NA011        2006-01-15 22:12:38   DANIELS
00123     NA012        2003-05-30 08:25:41   (704) 242-2124

谢谢你的帮助。

4

3 回答 3

1

也许是这样的:

SELECT
    t.*
FROM
    TABLE_1 AS t
    JOIN 
    (
        SELECT
            MAX(t2.EFFECTIVE_DATE) AS EFFECTIVE_DATE,
            t2.PROP_TYPE,
            t2.OID
        FROM
            TABLE_1 AS t2
        GROUP BY
            t2.PROP_TYPE,
            t2.OID
    ) AS MaxDate
    ON t.EFFECTIVE_DATE=MaxDate.EFFECTIVE_DATE
    AND t.PROP_TYPE=MaxDate.PROP_TYPE
    AND t.OID=MaxDate.OID
于 2012-04-24T14:00:41.190 回答
0
SELECT 
    t.*
FROM 
        TABLE_1 AS t
    JOIN
        ( SELECT oid, prop_type, MAX(effective_date) AS effective_date
          FROM TABLE_1 
          GROUP BY oid, prop_type
        ) AS g
      ON  (g.oid, g.prop_type, g.effective_date)
        = (t.oid, t.prop_type, t.effective_date)

上的索引(oid, prop_type, effective_date, prop_value)可能有助于提高性能。

于 2012-04-24T14:03:59.673 回答
0

尝试这个:

select OID, PROP_TYPE, EFFECTIVE_DATE, PROP_VALUE
  from TABLE_1
 where OID, PROP_TYPE, EFFECTIVE_DATE in
  (select OID, PROP_TYPE, MAX(EFFECTIVE_DATE) from TABLE_1 group by OID, PROP_TYPE)
于 2012-04-24T13:56:20.610 回答