0

我有 3 个表:UsersFriends和。MoviesUser_Movies

Users并且Movies只是用户和电影的列表。

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

User_Movies有 2 列:#user_id#movie_id并且有说“用户有电影”。

好的。现在我想选择每个用户,他的朋友和他的电影。我已经开始获取朋友的数量,但我也不知道如何获取电影的数量。任何人都可以帮忙吗?

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`;`

谢谢您的帮助。

4

1 回答 1

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
于 2012-09-11T20:53:12.037 回答