4

我的数据库中有三个表,请参见下面的结构:

用户

uid | fname | date_joined
---------------------------------
 1  | john  | 2013-08-25 01:00:00
 2  | rock  | 2013-08-26 01:00:00
 3  | jane  | 2013-08-27 01:00:00

问题

qid | uid 
---------- 
 1  |  1   
 2  |  1   
 3  |  2   
 4  |  3   
 5  |  3   
 6  |  1   
 7  |  1   
 8  |  2   
 9  |  2   

追随者

fid | qid
---------
 1  |  2
 2  |  1
 3  |  2
 4  |  1
 5  |  2
 6  |  3
 7  |  2

user 表包含所有与用户相关的字段
questions 表包含所有带有外键 uid 的问题相关数据 Followers
表存储问题关注次数的​​信息

我希望我的查询返回的是:

unique uid, 
fname
question count for each user
follower count for each user

我已经编写了一个查询,它工作正常,并根据需要返回记录,但关注者计数始终为 0。这是我的查询:

SELECT 
    u.uid, u.fname, u.date_joined , 
    (SELECT COUNT(*) FROM questions WHERE questions.uid = u.uid) AS question_count,
    (SELECT COUNT(*) FROM followers WHERE followers.qid IN ( 
        SELECT GROUP_CONCAT(qid) FROM questions WHERE questions.uid = u.uid 
        ) 
    ) AS follow_count
FROM epc_user AS u
ORDER BY follow_count DESC, question_count DESC, date_joined DESC

我尝试了几种不同的组合,但都没有奏效,也许我写了一个错误的查询,或者它不可能在另一个子查询中使用子查询,不管它可能是什么。我只想知道它是否可能以及是否可能

4

2 回答 2

3

GROUP_CONCAT将返回一个字符串,但IN运算符使用一组值而不是字符串,所以你必须使用这样的东西

   SELECT 
        u.uid, u.fname, u.date_joined , 
        (SELECT COUNT(*) FROM questions WHERE questions.uid = u.uid) AS question_count,
        (SELECT COUNT(*) FROM followers WHERE followers.qid IN ( 
            SELECT qid FROM questions WHERE questions.uid = u.uid 
            ) 
        ) AS follow_count
    FROM users AS u
    ORDER BY follow_count DESC, question_count DESC, date_joined DESC

小提琴:http ://sqlfiddle.com/#!2/8cd10/2

于 2013-08-31T09:28:25.530 回答
2

您可以使用连接来获取结果。不需要子查询:

select 
  u.uid, 
  u.fname, 
  u.date_joined, 
  count( distinct q.qid ) as 'question_count', 
  count( distinct f.fid ) as 'follower_count'
from users u
  left join questions q on q.uid = u.uid
  left join followers f on f.qid = q.qid
group by u.uid, u.fname, u.date_joined
order by follower_count desc, question_count desc, date_joined desc;
于 2013-08-31T09:33:48.020 回答