从mysql获取最新事件

时间:2014-04-28 11:08:39

标签: mysql

我有events表。我想要事件类型='约会'的最新事件以及typeinstruction_id上的组。问题是event_date首先出现'2013-12-02'而不是'2013-12-05'。需要更多信息给予评论我详细解释。

我的预期输出:

ID  INSTRUCTION_ID  TYPE    COMMENT     EVENT_DATE
3   2   appointment     at home     December, 05 2013 00:00:00+0000
10  1   appointment     at home     November, 22 2013 00:00:00+0000
5   3   appointment     office  September, 17 2013 00:00:00+0000

有关详细信息,请查看SQL fiddle

2 个答案:

答案 0 :(得分:1)

尝试以下查询:

select * 
from 
(SELECT * 
FROM EVENTS 
WHERE EVENTS.type='appointment'
ORDER BY EVENTS.event_date DESC) EVENTS
GROUP BY EVENTS.type,EVENTS.instruction_id;

查询2:

select * 
from 
(SELECT * 
FROM EVENTS 
WHERE EVENTS.type='appointment'
ORDER BY EVENTS.event_date DESC) EVENTS
GROUP BY EVENTS.type;

答案 1 :(得分:1)

如果您想要按事件类型进行最新的“约会类型”分组:

SELECT max(EVENT.event_date) -- use other fields
FROM EVENTS 
WHERE EVENTS.type='appointment'
GROUP BY EVENTS.instruction_id;

因为如果您按一种特定类型过滤,则只能获得该类型的最大日期。如果您想获得每种类型的最大日期

SELECT max(EVENT.event_date) -- use other fields
FROM EVENTS 
GROUP BY EVENTS.type, EVENTS.instruction_id

编辑:如果添加其余字段,则按预期工作。无论如何,我粘贴你测试的查询:

    SELECT ID, INSTRUCTION_ID, TYPE, COMMENT, max(EVENT_DATE) EVENT_DATE 
    FROM EVENTS 
    WHERE EVENTS.type='appointment'
    GROUP BY EVENTS.instruction_id
ORDER BY EVENT_DATE;