我有以下表格
1. user
+----+-------------------+
| id | email |
+----+-------------------+
| 2 | user1@example.com |
| 3 | user2@example.com |
| 1 | user3@example.com |
+----+-------------------+
2. answer
+----+---------+-------------+-----------+---------------------+
| id | user_id | question_id | option_id | created |
+----+---------+-------------+-----------+---------------------+
| 1 | 2 | 1 | 5 | 2015-12-19 15:15:07 |
| 2 | 2 | 1 | 5 | 2015-12-19 15:16:05 |
| 3 | 2 | 2 | 3 | 2015-12-19 15:16:06 |
| 4 | 2 | 3 | 3 | 2015-12-19 15:16:08 |
| 5 | 2 | 1 | 1 | 2015-12-19 15:32:46 |
| 6 | 2 | 1 | 4 | 2015-12-19 15:39:22 |
| 7 | 2 | 1 | 2 | 2015-12-19 15:39:23 |
| 8 | 2 | 1 | 2 | 2015-12-19 15:40:38 |
| 9 | 2 | 1 | 1 | 2015-12-19 15:41:25 |
+----+---------+-------------+-----------+---------------------+
我想获取option_id,其中大多数事件按用户分组并具有以下条件
参考上面的答案表,如您所见,option_id
最多出现四次,在这种情况下,我希望返回列表中的最后一个option_id 1
以下是我用来实现我想要的查询
SELECT
option_id,
COUNT(option_id) as occurence
FROM
answer
GROUP BY
option_id
ORDER BY
occurence DESC LIMIT 1;
这是有效的,但是当我添加WHERE条件时,它给了我option_id 5,而我期望option_id 1
SELECT
option_id,
COUNT(option_id) as occurence
FROM
answer
WHERE
user_id = 2
GROUP BY
option_id
ORDER BY
occurence DESC LIMIT 1;
我在这里缺少什么?
注意:这是此link的后续问题,我在此重新发布的原因是发布同一问题的简化版本。
答案 0 :(得分:2)
我在桌子上做了类似的事情,这是我的解决方案:
SELECT option_id
FROM answer
WHERE id = (SELECT id
FROM answer
WHERE user_id = 2
GROUP BY option_id
ORDER BY COUNT(option_id) DESC, id DESC
LIMIT 1)
或者查看在查询中ORDER BY occurence DESC, id DESC
会发生什么。
答案 1 :(得分:1)
一步一步:
查询:
select *
from answer
where option_id in
(
select option_id
from answer
group by option_id
having count(*) =
(
select count(*) as cnt
from answer
group by option_id
order by count(*) desc limit 1
)
)
order by created desc limit 1;
答案 2 :(得分:1)
如果它真的只是您感兴趣的order_id,则只需将MAX(created) DESC
添加到您的ORDER BY:
SELECT
option_id,
COUNT(option_id) as occurence
FROM
answer
WHERE
user_id = 2
GROUP BY
option_id
ORDER BY
occurence DESC, MAX(created) DESC LIMIT 1;