[英]Select from database with count and count based conditions?
I have a table with data relating to a user, and two important columns: 我有一个表,其中包含与用户有关的数据,以及两个重要的列:
refer_count
, which is updated when a new entry is made in the table with the referred_by
column set to that users user_id
, and referred_by
which is the user_id
of the of the user that referred them. refer_count
,当在表中创建一个新条目时将其更新,并且referred_by
列设置为该用户user_id
,并且referred_by
是引用他们的用户的user_id
。
I want to select the users from the table that have the highest number of referrals after a certain date. 我想从表中选择在特定日期后具有最高推荐人数的用户。
For example: 例如:
If there are 3 users, one of which referred the other 2 (lets say users 2
and 3
), however user 2 was referred on the 2/12/14, whereas user 3 was referred on the 3/1/15. 如果有3个用户,其中一个引用了另外2个用户(假设用户
2
和3
),则在2/12/14上引用了用户2,而在3/1/15上引用了用户3。
If the cutoff is 1/12/14, then user 1 is returned with refer_count set to 2, but if the cutoff is after 2/12/14, then user 1 is returned with refer_count set to 1. 如果截止时间是1/12/14,则返回用户1并将Refer_count设置为2,但是如果截止时间是14年2月12日,则返回用户1并将Refer_count设置为1。
I've been thinking of how to do this, but I can't think of a way that would work. 我一直在想如何做到这一点,但我想不出一种可行的方法。 Is there a way?
有办法吗?
This is via MySQL. 这是通过MySQL。
EDIT: I think I may need to provide for information. 编辑:我想我可能需要提供信息。
The date registered ( register_date
) is used as the refer date. 注册日期(
register_date
)被用作参考日期。 I need the refer_count to be updated with the number of users referred after the cutoff, however I need to get the actual user. 我需要使用截止日期后引用的用户数来更新Refer_count,但是我需要获取实际用户。 This is for a 'top referrers' table.
这是用于“最高引荐来源”表的。 I can't figure out why I'm having so much trouble thinking of a way to do this.
我不知道为什么我在想办法时遇到这么多麻烦。
SELECT user_id FROM usertable WHERE (referal_date BETWEEN '2014-12-2' AND CURDATE())ORDER BY refer_count DESC;
That's the rough idea. 那是个粗略的主意。 You should look into normalizing your tables if you're keeping that all in the same table, though.
但是,如果将所有表都放在同一个表中,则应考虑对其进行规范化。 It'd be better to keep referals in a seperate table.
最好将引荐保存在单独的表中。
Get the row with the maximum in refer_count
with a Date condition for your referal_date
such that it's after the certainDate
: 获取与最大的行
refer_count
为您的日期条件referal_date
,使得它的后certainDate
:
SELECT user_id FROM table WHERE refer_count = (SELECT MAX(refer_count) FROM table) AND referal_date>certainDate;
Note that WHERE
is before SELECT
so it will not get the highest count first, but will filter with the date condition then get the highest count. 请注意,
WHERE
在SELECT
之前,因此它不会首先获得最高计数,但是将使用日期条件进行过滤,然后获得最高计数。
Edit: Updated query based on edited question. 编辑:根据已编辑的问题更新查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.