mysql结合两个选择?

时间:2012-02-23 19:34:16

标签: 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

2 个答案:

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

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