Mysql or/and precedence?

后端 未结 4 1951
悲&欢浪女
悲&欢浪女 2020-11-22 15:41

I am wondering how or/and works?

For example if I want to get all rows where display = 1

I can just do WHERE tablename.display = 1

and i

4条回答
  •  庸人自扰
    2020-11-22 16:14

    The MySQL documentation has a good page with information on which operators take precedence.

    From that page,

    12.3.1. Operator Precedence

    Operator precedences are shown in the following list, from highest precedence to the lowest. Operators that are shown together on a line have the same precedence.

    INTERVAL
    BINARY, COLLATE
    !
    - (unary minus), ~ (unary bit inversion)
    ^
    *, /, DIV, %, MOD
    -, +
    <<, >>
    &
    |
    = (comparison), <=>, >=, >, <=, <, <>, !=, IS, LIKE, REGEXP, IN
    BETWEEN, CASE, WHEN, THEN, ELSE
    NOT
    &&, AND
    XOR
    ||, OR
    = (assignment), :=
    

    So your original query

    Select
        *
    from tablename 
    where
        display = 1
        or display = 2
        and content like "%hello world%"
        or tags like "%hello world%"
        or title = "%hello world%"
    

    would be interpreted as

    Select
        *
    from tablename 
    where 
        (display = 1)
        or (
            (display = 2)
            and (content like "%hello world%")
        )
        or (tags like "%hello world%")
        or (title = "%hello world%")
    

    When in doubt, use parenthesis to make your intent clear. While the information on the MySQL page is helpful, it may not be immediately obvious if the query is ever revisited.

    You might consider something like the following. Note that I've changed the title = "%hello world%" to title like "%hello world%", since that fits better with the goal you've described.

    Select
        *
    from tablename 
    where
        (
            (display = 1)
            or (display = 2)
        ) and (
            (content like "%hello world%")
            or (tags like "%hello world%")
            or (title like "%hello world%")
        )
    

提交回复
热议问题