gpt4 book ai didi

Mysql 按两列进行分组,其中条件为第三列的最大日期

转载 作者:行者123 更新时间:2023-11-29 09:51:20 26 4
gpt4 key购买 nike

我有一个表,其中包含 user_id、item_id 和 last_date 作为列。最后一个列类型采用日期时间

我需要通过对 user_iditem_id 列进行分组来检索 last_date,条件 type_id 类似于 < 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

最佳答案

下面是一种方法 -

    SELECT 
from MyTable t1
INNER JOIN
(
SELECT user_id,
item_id,
max(last_date) AS lastdate
FROM MyTable
WHERE type_id='foo'
GROUP BY user_id,
item_id) t2
ON t1.user_id=t2.user_id
AND t1.item_id=t2.item_id
AND t1.last_date=t2.lastdate

关于Mysql 按两列进行分组,其中条件为第三列的最大日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54742809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com