连接表中的一列不受WHERE子句,My SQL

时间:2017-03-09 17:02:48

标签: mysql inner-join

我有以下代码:

SELECT YEAR(user.reg_date) AS year,
    MONTH(user.reg_date) AS month,
    DATE (
        CASE 
            WHEN DAYOFWEEK(user.reg_date) >= 2
                THEN DATE_SUB(user.reg_date, INTERVAL(DAYOFWEEK(user.reg_date) - 2) DAY)
            ELSE DATE_ADD(user.reg_date, INTERVAL 1 DAY)
            END
        ) AS week_of,
    count(*) AS signups,
    COUNT(CASE 
            WHEN user.gender = 'M'
                THEN user.user_id
            END) AS males,
    COUNT(CASE 
            WHEN user.gender = 'F'
                THEN user.user_id
            END) AS females,
    (
        SELECT COUNT(*)
        FROM unsubscribe
        INNER JOIN user ON user.token = unsubscribe.token
        WHERE DATE (DATETIME) BETWEEN week_of
                AND DATE_ADD(week_of, INTERVAL 6 DAY)
        ) AS unsubscribe
FROM user
INNER JOIN place ON user.place_id = place.place_id
WHERE user.reg_date IS NOT NULL
    AND YEAR(user.reg_date) >= YEAR(CURDATE()) - 2
    AND place.contained_by = '207'
GROUP BY CONCAT (
        YEAR(user.reg_date),
        '/',
        WEEK(user.reg_date)
        )
ORDER BY week_of;

我的最终表结果几乎可以正常工作,但是在连接表中名为unsubscribe的列不受最后一个where语句的影响/未过滤,我不知道为什么。

EDITED: 这是我得到的结果。架构是正确的,但所有列都通过place_id EXCEPT进行过滤以取消订阅。我需要取消订阅才能通过place_id进行过滤。

|year |month |week_of    |signups |males |females |unsubscribe |
|2015 |1     |2014-12-29 |5       |1     |4       |269         |

1 个答案:

答案 0 :(得分:0)

我相信您需要根据user表中的place_id将子查询与WHERE子句中的主查询相关联。您正在主查询中过滤您的位置表,并且您已经加入子查询中的用户表,因此您可以使用user.place_id在WHERE子句中执行此操作。

 SELECT COUNT(*)
 FROM unsubscribe INNER JOIN user  
     ON user.token = unsubscribe.token
 WHERE DATE (DATETIME) BETWEEN week_of
     AND DATE_ADD(week_of, INTERVAL 6 DAY)
     AND user.place_id = place.place_id