Jethro Hazelhurst Jethro Hazelhurst - 2 months ago 5
SQL Question

MySql exclude a result with a certain ID?

Here is my SQL statement

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')


As you can see, I want to exclude any results with a certain ID, however this seems to not be working because...

enter image description here

Shouldn't this behave as expected??

Answer

You obviously don't understand Operator Precedence

You can rarely mix AND and OR operators in the same instruction, without specifying their scope with parenthesis.

Properly indenting your code following the parenthesis also help to understand your query:

    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')
        )
Comments