1

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.

Nick
  • 138,499
  • 22
  • 57
  • 95
  • 2
    The problem is in the way the AND and OR conditions are being processed. – Nigel Ren Dec 23 '18 at 20:12
  • Possible duplicate of [Mysql or/and precedence?](https://stackoverflow.com/questions/12345569/mysql-or-and-precedence) – Nick Dec 23 '18 at 23:09

2 Answers2

3

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.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
2

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)
Mureinik
  • 297,002
  • 52
  • 306
  • 350