MySQL - 从一个表中选择COUNT来自另外两个

时间:2012-09-11 20:48:05

标签: mysql join

我有3个表:UsersFriendsMoviesUser_Movies

UsersMovies只是一个用户和电影列表。

Friends只有两列: #fan_id#idol_id ,只是说“用户1跟随用户2”。

User_Movies有2列: #user_id#movie_id ,可以说“用户有电影”。

确定。现在我想选择每个用户,COUNT他的朋友和他的电影。我已经开始得到朋友的数量,但我不知道如何获得电影的数量。有人可以帮忙吗?

SELECT u.`id`, u.`username`, COUNT(*) AS n_relation
FROM `users` u
JOIN `friends` f ON f.`idol_id` = u.`id`
OR f.`fan_id` = u.`id`
WHERE `username` = ?
GROUP BY u.`id`;`

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

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