2012-02-23 53 views
0

的第一选择是mysql结合了两个选择?

select user_id, count(*) as count 
from users 
where referrer IS NOT NULL 
group by referrer 
order by count DESC 

然后基于关闭的该查询,我需要得到谁在上面的查询提到的用户,用户的返回日期的记录。

select user_id from users where token = IDS_FROM_LAST_QUERY 

我知道我可以使用子查询,并说哪里IN(子查询),但我越来越绊倒试图保持计数从子查询。

所以最终我需要以下信息

user_id, count 

回答

1
select o.user_id user_id, count(*) count 
from users o 
join users i on o.token = i.user_id 
where i.referrer is not null 
group by referrer 
order by count desc 
+0

我将连接修改为o.token = i.referrer。 – hcker2000 2012-02-23 19:42:06

0

我会用一个CTE(公共表表达式)。 CTE是非常方便的,希望得到一个人口,然后查询与CTE相同或略有不同的人口。

WITH Referrer (user_id, count) AS 
(
select user_id, count(*) as count 
from users 
where referrer IS NOT NULL 
group by referrer 
order by count DESC 
) 

select 

users.user_id 
,Referrer.count 

from users 

inner join Referrer.user_id = users.user_id