如何在mysql中使用三个表的另一个子查询中使用子查询?

时间:2013-08-31 08:52:17

标签: mysql sql database subquery nested-queries

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

用户

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

用户表包含所有与用户相关的字段
问题表包含与外键uid的所有问题相关数据 粉丝表存储了一个问题跟随的次数的信息

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

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

我尝试了几种不同的组合,但它们都没有工作,也许我正在编写一个错误的查询,或者它不可能在另一个子查询中使用子查询,无论它是什么。我只是想知道它是否可能,如果可能的话

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

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