select
u.*,
(select count(*) from friends f where f.idol_id = u.id) as fancount,
(select count(*) from user_movies m where m.user_id = u.id) as moviecount
from
users u
where
u.username = 'j.doe'
或者,这可能会更快(但您应该测试您的数据库中是否是这种情况):
select
u.*,
uf.fancount,
um.moviecount
from
users u
left join
(select
f.idol_id, count(*) as fancount
from friends f) uf on uf.idol_id = u.id
left join
(select
m.user_id, count(*) as moviecount
from user_movies m) um on um.user_id = u.id
where
u.username = 'j.doe'
第三种选择,看起来像您的尝试和 desimusxvii 的尝试,只有它使用distinct
“修复”计数问题,当您有多个朋友时,电影会被多次计数,反之亦然。不过,我建议不要使用此选项,因为查询的可读性和可维护性较差。group by
它在不需要的时候滥用。
select
u.username,
count(distinct f.fan_id) as fancount,
count(distinct m.movie_id) as moviecount
from
users u
left join friends f on f.idol_id = u.user_id
left join user_movies m on m.user_id = u.user_id
where
u.username = 'j.doe'
group by
u.username