简体   繁体   中英

Why does mySQL query give unexpected results?

This is my mySQL query :

SELECT mCat,postSta 
FROM `info_posts` 
WHERE `mCat` = 'Mobiles' AND `sCat` = 'Mobile Phones' AND `brCat` = 'Apple' AND `postSta` = 1 OR `postSta` = 4 OR `postSta` = 5

The problem with this is that it selects all the criteria properly however it also fetches the things where postSta = 4 and 5 take a look at the screenshot . I want to select things which match the criteria of mCat,sCat and brCat where postSta is 1 or 4 or 5.

Use IN :

SELECT mCat,postSta
FROM info_posts
WHERE mCat = 'Mobiles' AND sCat = 'Mobile Phones' AND brCat = 'Apple' AND 
      postSta IN (1, 4, 5)

The problem is that you need parentheses in your query, but IN is a better approach.

The logical "and" operation has a higher precedence than the logical "or" operator. The logic you're looking for can be achieved by surrounding the series of "or" conditions with parenthesis:

SELECT `mCat`, `postSta`
FROM   `info_posts`
WHERE  `mCat` = 'Mobiles' AND
       `sCat` = 'Mobile Phones' AND
       `brCat` = 'Apple' AND
       (`postSta` = 1 OR `postSta` = 4 OR `postSta` = 5)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM