查询最近X天内具有相同值的组数据

时间:2017-10-04 13:50:01

标签: mysql sql

我想在过去的14天里从我的表中获得最常用的5个model_id的列表。问题是,我无法找到一种方法来对model_id进行分组,以避免在结果中多次使用model_id次。

媒体表

+----+-------+----------+---------------------+
| id | title | model_id |        date         |
+----+-------+----------+---------------------+
|  1 |   ... |        1 | 2017-10-04 01:47:46 |
|  2 |   ... |        1 | 2017-10-03 02:47:46 |
|  3 |   ... |        2 | 2017-10-02 03:47:46 |
|  4 |   ... |        2 | 2017-10-02 02:47:46 |
|  5 |   ... |        3 | 2017-10-01 04:47:46 |
+----+-------+----------+---------------------+

到目前为止这是我的代码(不起作用)

SELECT COUNT(medias.model_id), medias.date
FROM medias
GROUP BY medias.model_id HAVING COUNT(medias.model_id) > 1
WHERE date > DATE_SUB(CURDATE(), INTERVAL 14 DAY)

1 个答案:

答案 0 :(得分:0)

查找计数并使用LIMIT选择最上一个。

<强>查询

select `model_id`, count(*) as `total`
from `medias`
where `date` > DATE_SUB(CURDATE(), INTERVAL 14 DAY)
group by `model_id`
order by `total` desc limit 1;