从mysql中的非规范化数据中选择最新的

时间:2012-03-29 13:58:07

标签: mysql sql

我在mysql中有一个表没有规范化,我需要进行查询,以便按特定字段进行分组并给出最近的行。

例如,该表看起来像

callername | callerdate | incoming | status

我正在努力获取最新状态为NotAnswered的所有记录,而我无法弄清楚你将如何做到这一点,我可以GROUP BY来电,但我可以'弄清楚如何获得最新的价值。

感谢。

2 个答案:

答案 0 :(得分:2)

SELECT A.* FROM
YOURTABLE A,
( 
SELECT callername,callerdate,MAX(ID) AS ID 
FROM YOURTABLE
WHERE status='NotAnswered'
GROUP BY callername,callerdate
) B
WHERE A.ID=B.ID;

答案 1 :(得分:1)

SELECT
  yourTable.*
FROM 
  yourTable
INNER JOIN
(
  SELECT
    callername,
    MAX(callerdate) AS callerdate
  FROM
    yourTable
  GROUP BY
    calledname
)
  AS mostRecent
    ON  mostRecent.callername = yourTable.callername
    AND mostRecent.callerdate = yourTable.callerdate
WHERE
  yourTable.status='NotAnswered'