2012-02-23 71 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