LEFT JOIN过滤了过去30天加入的推荐人,而不是过去30天加入的推荐人

时间:2015-10-23 11:07:44

标签: php mysql sql left-join

我有2张桌子

表用户

USER_ID------USERNAME------------REGISTERTIME  
1-----------------admin----------1432985224    
2-----------------test ----------1433985224
3-----------------test2----------1332985224     

表REFERRALS

REFERRER_ID----------REFERRAL_ID 
1-----------------------------2
1-----------------------------3

如何用mysql显示:

user admin have 2 referrals in last 30 days
user test  have 0 referrals in last 30 days
user test2 have 0 referrals in last 30 days

尝试:

SELECT
    users.username,
    COUNT(referrals.user_id) AS referrals
FROM
    users
LEFT JOIN
    referrals ON
    referrals.referral_id = users.user_id
WHERE users.registertime >= UNIX_TIMESTAMP( '2015-10-15' ) AND registertime < UNIX_TIMESTAMP( '2015-10-18' )
GROUP BY
    users.user_id

它显示的是

仅限过去30天加入并推荐的用户 但我需要它显示所有用户在过去30天内有新推荐

错误:(这仅显示过去30天内加入并推荐的用户)

new user1 have 12 referrals new user2 have 3 referrals new user3 have 2 referrals

正确:(这表示所有在过去30天内加入推介的用户)

Old user1 have 52 referrals New user3 have 28 referrals Old user33 have 10 referrals

我希望我解释清楚

2 个答案:

答案 0 :(得分:1)

您需要引入有关引荐来源的信息并将其用于过滤

SELECT u.username, COUNT(*) AS referrals
FROM users u JOIN
     referrals r
     ON r.referral_id = u.user_id JOIN
     users ur
     ON r.referrer_id = ur.user_id AND
        ur.registertime >= UNIX_TIMESTAMP( '2015-10-15' ) AND
        ur.registertime < UNIX_TIMESTAMP( '2015-10-18' )
GROUP BY u.username;

我认为你不需要LEFT JOIN。你的例子都没有0个计数。如果您也需要它们,那么只需更改查询中的连接。

您还应养成使用GROUP BY中与SELECT中使用的相同列的习惯。这是一个可以防止将来出错的好习惯。

答案 1 :(得分:-1)

SELECT
    users.username,
    COUNT(referrals.referrer_id) AS referrals
FROM
    users
LEFT JOIN
    referrals ON
    referrals.referrer_id = users.user_id
WHERE users.registertime >= UNIX_TIMESTAMP( '2015-10-15' ) AND registertime < UNIX_TIMESTAMP( '2015-10-18' )
GROUP BY
    users.user_id