Mysql - where子句中的忽略状态

时间:2015-02-09 17:17:19

标签: mysql

我尝试使用此查询从所选健身房获取所有用户。

我的问题是忽略此部分的查询:ual.user_id = weekUsers.user_id

似乎查询将所有用户ID与我选择的日期相匹配,而不检查此用户是否在我想要选择的健身房中。

在我放的图片中,您可以看到ual.user_idweekUsers.user_id不相等,但我仍然在结果中得到它们。

这是我的问题:

SELECT count(ual.user_id), FROM_DAYS(TO_DAYS(ual.time) -MOD(TO_DAYS(ual.time) -1, 7)) as weekNum, 

        ual.user_id, weekUsers.user_id, u.id, u.gym

        FROM user_activity_log ual

        LEFT OUTER JOIN user u

        ON u.gym = 3

        LEFT OUTER JOIN (SELECT ualWeek.user_id FROM user_activity_log ualWeek 

        GROUP BY FROM_DAYS(TO_DAYS(ualWeek.time) -MOD(TO_DAYS(ualWeek.time) -1, 7)), ualWeek.user_id 

        HAVING count(ualWeek.user_id) > 1) weekUsers

        ON u.id = weekUsers.user_id

        WHERE 

        (ual.time BETWEEN '2014-02-09' AND '2015-02-09') OR (('2014-02-09' IS NULL) OR ('2015-02-09' IS NULL))

        AND ual.user_id = weekUsers.user_id

        GROUP BY ual.user_id

enter image description here

1 个答案:

答案 0 :(得分:1)

让我们解释你的(ual.time BETWEEN '2014-02-09' AND '2015-02-09') OR (('2014-02-09' IS NULL) OR ('2015-02-09' IS NULL))表达式。

(ual.time BETWEEN '2014-02-09' AND '2015-02-09')称为A,将(('2014-02-09' IS NULL) OR ('2015-02-09' IS NULL))称为B,我们得到A or B

所以我们有A or B AND ual.user_id = weekUsers.user_id

由于默认操作优先级,它将被解释为A or (B AND ual.user_id = weekUsers.user_id),因此如果A为真,那么整个逻辑表达式为真,并且不会检查ual.user_id = weekUsers.user_id,只是忽略。

您可以参考http://www.bennadel.com/blog/126-sql-and-or-order-of-operations.htmhttp://www.bennadel.com/blog/126-sql-and-or-order-of-operations.htm 有关运算符优先级的更多详细信息。