Multiple MySql WHERE Between Clauses

前端 未结 3 762
暗喜
暗喜 2021-01-01 05:05

Newbie MySql programmer thanks for the patience.

Im trying to track an Id number in a table where 3 different conditions are met this is what Iv got however the quer

相关标签:
3条回答
  • 2021-01-01 05:24

    I think the range needs to be the other way around:

    SELECT * FROM table WHERE x BETWEEN 20 AND 80 AND y BETWEEN 20 AND 120 AND z BETWEEN 10 AND 40 LIMIT 0 , 30
    
    0 讨论(0)
  • 2021-01-01 05:35
    SELECT * FROM table WHERE 
          (x BETWEEN 20 AND 80) AND 
          (y BETWEEN 20 AND 120) AND 
          (z BETWEEN 10 AND 40) 
    LIMIT 0 , 30
    
    0 讨论(0)
  • 2021-01-01 05:38

    Close, but no cigar. :)

    SELECT * FROM table 
    WHERE (x BETWEEN 20 AND 80) AND 
    (y BETWEEN 20 AND 120) AND 
    (z BETWEEN 10 AND 40) LIMIT 0 , 30
    

    To explain, SQL servers generally evaluate x BETWEEN val1 AND val2 the same as x >= val1 AND x <= val2. The way your original query was written, the first condition would be x >= 120 AND x <= 20), which obviously wasn't what you intended.

    The parentheses around the different conditions make sure that each is evaluated completely before the AND is considered. It makes a difference most of the time in SQL, and even when it doesn't it's a good idea to use them so your intentions are clear 6 months from now when you (or someone else) has to look at the query again.

    0 讨论(0)
提交回复
热议问题