尝试按SQL中的最新日期字段进行分组,其中另一个字段相等

时间:2013-11-24 04:13:19

标签: mysql sql group-by where

嘿,我遇到了一个问题 - 我觉得只有分组才会很容易,但是当时间是游戏中的一个因素时,它会多一点。

我正在尝试获取不同mainQuestion_id上的所有记录,这些记录可能具有不同时间戳(和id ofc)的重复项。这应该被过滤,所以我得到那些等于activationCode_id,而不是一个子字幕,这是字段subQuestion_id

所以我想说我有这张桌子

CREATE TABLE surveys_answer
    (`id` int, `activationCode_id` int, `mainQuestion_id` int, `subQuestion_id` int,   `timestamp` int);

INSERT INTO surveys_answer
    (`id`,  `activationCode_id`, `mainQuestion_id`, `subQuestion_id`, `timestamp`)
VALUES
 (1, 1, 4, 0, 201313),
 (2, 1, 4, 0, 201314),
 (3, 2, 3, 1, 201315),
 (4, 2, 4, 0, 201316),
 (5, 1, 9, 1, 201317),
 (6, 1, 6, 0, 201318),
 (7, 1, 4, 1, 201319);

我希望结果为latest by time or id which have activationCode_id = 1 and where subQuestion_id = 0

我想要的是

2, 1, 4, 0, 201314

6, 1, 6, 0, 201318

我一直在尝试分组,错过(2,1,4,0​​,201314)并拿下第一个(1,1,4,0​​,201313),这不是我想要的

我认为这样可行:

SELECT * FROM surveys_answer 
WHERE activationCode_id = 1
AND subQuestion_id = 0
group by mainQuestion_id

我一直试图让它发挥作用:

SELECT  a.*
FROM    surveys_answer a
    INNER JOIN
    (
        SELECT  max(id) xx, mainQuestion_id
        FROM    surveys_answer 
        GROUP   BY mainQuestion_id
    ) b ON  a.mainQuestion_id = b.mainQuestion_id AND 
            a.id = b.xx AND a.activationCode_id = '1' AND a.subQuestion_id = 0

但这给了我零结果

http://www.sqlfiddle.com/#!2/3e1cd

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

可能你可以试试这个

SELECT surveys_answer .* , max(timestamp) as mx_time FROM surveys_answer 
WHERE activationCode_id = 1
AND subQuestion_id = 0
group by timestamp 

答案 1 :(得分:0)

SELECT sa.*
FROM surveys_answer sa
WHERE timestamp = (
                   SELECT MAX(sa2.timestamp)
                   FROM surveys_answer sa2
                   WHERE sa2.activationCode_id = 1 AND sa2.subQuestion_id = 0 AND
                   sa2.mainQuestion_id = sa.mainQuestion_id
                  );

SQL Fiddle

基于您的样本数据的结果:

| ID | ACTIVATIONCODE_ID | MAINQUESTION_ID | SUBQUESTION_ID | TIMESTAMP |
|----|-------------------|-----------------|----------------|-----------|
|  2 |                 1 |               4 |              0 |    201314 |
|  6 |                 1 |               6 |              0 |    201318 |