简体   繁体   中英

How can I write a query for the following scenario?

I have a table that looks like this - http://d.pr/jQ1P and then another table (let's call it "actions" table) that contains a list of things that all users have done.

How can I write a query that can give me a count of how many new users referrer_id "1" has referred that also has at least 1 entry in the "actions" table? Eg. For referrer_id "1", "1723" and "1724" both have at least 1 row in the "actions" table, but not "1725. So for user "1", he has successfully referred 2 users, even though there's also "1725".

Hope that makes sense.

Using a JOIN, you know that if there is a row, then at least 1 row matched in the JOIN table. You can combine that with a GROUP BY to pull unique ids. I have a feeling this could be a in a much more efficient way, but the first thing that comes to mind is:

SELECT 
    COUNT(referrals.new_user_id) 
FROM 
    referrals
    JOIN actions ON actions.user_id = referrals.new_user_id 
WHERE 
    referrals.referrer_id = 1
GROUP BY referrals.new_user_id;

Edit: After thinking about it for a bit, assuming everything is indexed, I can't think of a more efficient solution. Some mild googling suggests that COUNT(DISTINCT referrals.new_user_id) might be faster instead of using the GROUP BY.

Here you go:

SELECT
  COUNT(DISTINCT r.new_user_id)  
FROM
  referral r    
  JOIN actions a ON a.fk_userid = r.new_user_id 
WHERE 
  r.referrer_id = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM