我需要获得前3个推荐人以及他的推荐人数,但只有合格人员(表2)。 我希望这是有道理的。到目前为止,我有以下查询。请帮忙。谢谢
SELECT count(*) as total_referrals, referrer
FROM table_1
WHERE table_2.qualified = '1'
GROUP BY referrer
ORDER BY total_referrals DESC
LIMIT 0,3
TABLE_1
referrer referral
user1 user89
user1 user54
user1 user23
user1 user56
user2 user89
user2 user23
user2 user45
user3 user78
user3 user14
user4 user10
user5 user98
user5 user56
...
TABLE_2
referral qualified
user89 1
user54 0
user23 0
user56 1
user89 1
user23 1
user45 0
user78 1
user14 1
user10 0
user98 1
user56 1
...
答案 0 :(得分:1)
您需要引用from子句中的两个表,并确定您的字段名称是引用者还是用户名:
SELECT count(table_1.referrals) as total_referrals, referrer
FROM table_1 left join table_2 on table_1.referrals=table_2.referrals
WHERE table_2.qualified = '1'
GROUP BY table_1.referrer
ORDER BY total_referrals DESC
LIMIT 0,3
答案 1 :(得分:0)
更新2
http://sqlfiddle.com/#!9/2f598/5
以下查询似乎可以完成这项工作:
SELECT aa.referrer, COUNT(*) AS total_referrals
FROM table_1 AS aa
INNER JOIN (
SELECT referral
FROM table_2
WHERE qualified = 1
GROUP BY referral
) AS _bb
ON aa.referral = _bb.referral
GROUP BY aa.referrer
ORDER BY total_referrals DESC
LIMIT 3;