MYSQL返回越界日期

时间:2017-07-24 15:35:12

标签: mysql

我有一个具有以下结构的数据库表:

user_id (int) | status (int) | param1 (varchar) | param2 (varchar) | start (date) | external_id (int)

我正在执行以下查询:

DB表具有以下结构。

select
    * 
from
    `users_stuff` 
where
    (
        `status` >= '8' 
        and `start` between '2017-07-01' and '2017-07-11' 
        and `outside_url` is not null 
        and (
            `param1` = '1' 
            and `param2` = 'A'
        ) 
        or (
            `param1` = '0' 
            and `param2` = 'B'
        ) 
        and `user_id` = '14' 
        and `external_id` is not null
    ) 
    and `deleted_at` is null

然而,当结果返回给我时,我看到“开始”设置为7月12日的项目。这是为什么?这会导致什么错误?

谢谢!

3 个答案:

答案 0 :(得分:1)

我认为OR条件的放置正在招致这种行为。我已将更新查询更新如下:

select
    * 
from
    `users_stuff` 
where
    (
        `status` >= '8' 
        and `start` between '2017-07-01' and '2017-07-11' 
        and `outside_url` is not null 
        and (
            `param1` = '1' 
            and `param2` = 'A'

        or 
            `param1` = '0' 
            and `param2` = 'B'
        ) 
        and `user_id` = '14' 
        and `external_id` is not null
    ) 
    and `deleted_at` is null

答案 1 :(得分:1)

  

这会导致什么问题?

您的查询乍一看看起来有问题并且可能导致意外行为,例如您

`status` >= '8' 

然而,statusint,而不是string。所有其他整数都会出现同样的情况,这些整数在您的任务中引用了未知原因。因此修复语法并删除整数周围的所有引号,即表示

`status` >= '8' 

成为

`status` >= 8 

PS:作为小型“优化”,我会在and子句的开头移动is null deleted_at wherewhere deleted_at is null and ... as如果deleted_at不为空,那么评估剩余条件是没有意义的。

答案 2 :(得分:0)

在AND之后看看你的OR。 将您的OR语句包含在()。

之间

例如WHERE(AND标准OR标准)和标准。