MySql会排除具有特定ID的结果吗?

时间:2016-09-09 09:02:29

标签: php mysql sql

这是我的SQL语句

            SELECT * FROM schedule
            WHERE teacher_id = '$teacher_id'
            AND event_id <> '$event_id'
            AND seconds_start = '$start_time'
            OR (seconds_start < '$start_time' AND seconds_end > '$start_time')
            OR (seconds_start < '$end_time' AND seconds_end >= '$end_time')

正如您所看到的,我想要排除任何带有特定ID的结果,但这似乎不起作用,因为......

enter image description here

这不应该像预期的那样行事吗?

3 个答案:

答案 0 :(得分:3)

你显然不理解Operator Precedence

您很少在同一条指令中混合ANDOR运算符,而不用括号指定其范围。

在括号后正确缩进代码也有助于理解您的查询:

    SELECT * FROM schedule
    WHERE teacher_id = '$teacher_id'
      AND event_id <> '$event_id'
      AND ( 
             seconds_start = '$start_time'
         OR (seconds_start < '$start_time' AND seconds_end > '$start_time')
         OR (seconds_start < '$end_time' AND seconds_end >= '$end_time')
        )

答案 1 :(得分:1)

也许您需要对second_start

进行分组
    SELECT * FROM schedule
    WHERE teacher_id = '$teacher_id'
    AND event_id <> '$event_id'
    AND (seconds_start = '$start_time'
    OR (seconds_start < '$start_time' AND seconds_end > '$start_time')
    OR (seconds_start < '$end_time' AND seconds_end >= '$end_time'))

答案 2 :(得分:1)

您的OR部分会使您的陈述忽略您对event_id的限制。

正如Jon Stirling指出的那样,你需要相应地设置括号。

    SELECT * FROM schedule
    WHERE teacher_id = '$teacher_id'
    AND event_id <> '$event_id'
    AND (
        seconds_start = '$start_time'
        OR (seconds_start < '$start_time' AND seconds_end > '$start_time')
        OR (seconds_start < '$end_time' AND seconds_end >= '$end_time')
    )