【发布时间】:2019-02-18 08:06:33
【问题描述】:
我有一个表,其中包含 user_id、item_id 和 last_date 作为列。最后的列类型在 datetime 中。
我需要通过将列 user_id 和 item_id 与 type_id 类似的条件分组来检索 last_date strong>foo 非常重要,我需要在结果中包含所有列,因为在 mytable 中有更多列。
这是 mytable 结构:
user_id item_id last_date type_id
129678 2 2019-02-17 11:00:09 foo
129678 1 2019-02-17 11:00:15 foo
129678 2 2019-02-17 11:00:10 bar
129678 2 2019-02-17 11:00:10 bar
129678 2 2019-02-17 11:00:11 foo
129678 2 2019-02-17 11:00:15 foo
129678 1 2019-02-17 11:00:09 foo
129678 2 2019-02-17 11:00:14 bar
129678 2 2019-02-17 11:00:08 bar
129678 2 2019-02-17 11:00:11 foo
129678 2 2019-02-17 11:00:14 bar
129678 2 2019-02-17 11:00:10 foo
12a0d8 3 2019-02-17 11:00:08 foo
12a0d8 2 2019-02-17 11:00:12 foo
12a0d8 3 2019-02-17 11:00:08 bar
12a0d8 3 2019-02-17 11:00:12 bar
12a0d8 1 2019-02-17 11:00:10 foo
12a0d8 1 2019-02-17 11:00:11 bar
12a0d8 3 2019-02-17 11:00:14 foo
12a0d8 3 2019-02-17 11:00:12 foo
18ae98 2 2019-02-17 11:00:12 foo
18ae98 3 2019-02-17 11:00:07 bar
18ae98 1 2019-02-17 11:00:13 bar
18ae98 1 2019-02-17 11:00:14 foo
18ae98 2 2019-02-17 11:00:09 foo
18ae98 2 2019-02-17 11:00:13 foo
18ae98 3 2019-02-17 11:00:08 foo
18ae98 1 2019-02-17 11:00:12 foo
18ae98 3 2019-02-17 11:00:10 foo
18ae98 1 2019-02-17 11:00:12 foo
这是我为此尝试的查询:
SELECT * FROM mytable
WHERE last_date IN (
SELECT MAX(last_date)
FROM mytable
WHERE type_id LIKE 'foo'
GROUP BY user_id, item_id
)
想要的结果:
user_id item_id last_date type_id
129678 1 2019-02-17 11:00:15 foo
129678 2 2019-02-17 11:00:15 foo
12a0d8 1 2019-02-17 11:00:10 foo
12a0d8 2 2019-02-17 11:00:12 foo
12a0d8 3 2019-02-17 11:00:14 foo
18ae98 1 2019-02-17 11:00:14 foo
18ae98 2 2019-02-17 11:00:13 foo
18ae98 3 2019-02-17 11:00:10 foo
但是结果很奇怪!!例如,为 user_id 返回多个具有相同值的 item_id...
编辑:
如果我使用这个可以很好地工作的查询,但我必须指定一个间隔日期。
SELECT * FROM mytable
WHERE type_id LIKE 'foo'
AND last_date > date_sub(curdate(), interval 2 day)
GROUP BY user_id, item_id
【问题讨论】:
-
您使用的是哪个 MySQL 版本?
-
指定预期结果,表格数据如上。
-
@jarlh 我正在使用两个版本:v5.1.47(开发),v5.7.19(产品)。为了得到想要的结果,我更新了我的问题。
-
我已经用临时解决方案编辑了我的问题。
标签: mysql sql group-by max aggregate-functions