我想在过去的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)
答案 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;