Mysql计数从两个表连接一个用户ID

时间:2014-04-21 09:11:06

标签: php mysql

我想从现有的两个表中返回一个user_id的关注者和跟随数字,其中一个是用户,另一个是跟随:

我的代码在这里

SELECT users.id,
       users.name,
       COUNT(folow.following),
       COUNT(folow.follower)
FROM users
JOIN folow ON folow.following = users.id
WHERE users.id = '$other' LIMIT 10

1 个答案:

答案 0 :(得分:1)

在这里使用相关子查询可能最简单:

SELECT id,
       name,
       (SELECT COUNT(*) FROM folow WHERE following = users.id) followers,
       (SELECT COUNT(*) FROM folow WHERE follower  = users.id) following
FROM   users
WHERE  id = ?