我有两个表用户和投票,有些用户可以拥有相同的unq_id
我尝试从用户中选择所有不同 votes
,然后从投票1}}中对其进行排序 table。
但结果不是我的预期,投票是重复的。您可以在下图中看到
SELECT DISTINCT u.unq_id, COUNT(v.id) AS count_votes
FROM users u
INNER JOIN votes v
ON u.unq_id = v.unq_id
WHERE u.unq_id <> ''
GROUP BY u.unq_id;
预期结果:
3fyx6 - 3
9kx9mq - 1
答案 0 :(得分:3)
尝试更改
SELECT DISTINCT u.unq_id, COUNT(v.id) AS count_votes
到
SELECT DISTINCT u.unq_id, COUNT(distinct v.id) AS count_votes
看看是否有帮助:)
答案 1 :(得分:2)
要获得所需的结果,您无需加入users
,但根据您的评论“某些用户根本没有投票,我想将它们列入列表”你应该在LEFT加入之前聚合:
SELECT DISTINCT
u.unq_id,
COALESCE(v.count_votes, 0)
FROM users u
LEFT JOIN
( select unq_id, count(*) as count_votes
from votes
group by unq_id
) v
ON u.unq_id = v.unq_id
WHERE u.unq_id <> '';
答案 2 :(得分:1)
这样可行:
select distinct v.unq_id, count(distinct v.id) as votes
from users u
inner join votes v
on u.unq_id = v.unq_id
group by v.unq_id
order by 2 desc;
但我宁愿使用子查询,我认为它会更快:
select v.unq_id, count(v.unq_id) as votes
from votes v
where v.unq_id in (select unq_id from users group by unq_id)
group by v.unq_id
order by 2 desc;