简体   繁体   English

如何为以下情况编写查询?

[英]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. 我有一个看起来像这样的表-http: //d.pr/jQ1P ,然后是另一个表(我们称其为“动作”表),其中包含所有用户已完成的操作的列表。

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? 我该如何编写一个查询,该查询可以为我提供一个新的计数,即referrer_id“ 1”引用了多少个新用户,并且在“ actions”表中也至少有1个条目? 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". 对于Referrer_id“ 1”,“ 1723”和“ 1724”在“操作”表中都至少有1行,但没有“ 1725”。因此,对于用户“ 1”,他已经成功推荐了2个用户,即使还有“ 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. 使用JOIN,您知道如果有一行,那么JOIN表中至少有1行匹配。 You can combine that with a GROUP BY to pull unique ids. 您可以将其与GROUP BY结合使用以提取唯一ID。 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. 一些轻微的谷歌搜索建议使用COUNT(DISTINCT referrals.new_user_id)可能会更快,而不是使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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