0
SELECT * FROM table WHERE column LIKE '%whatever%' AND id='1' OR id='2' OR id='3'

When using the code above, I get back three rows and not the one with
column LIKE '%whatever%'
I find it strange, and can not understand why.

How could I rewrite my sql code to use LIKE to check in sevral rows that have id='whatever'

I use MYSQL and MyISAM

Alvin Wong
  • 12,210
  • 5
  • 51
  • 77
Joel
  • 61
  • 3
  • 11

2 Answers2

6

You need parentheses:

SELECT *
FROM table
WHERE column LIKE '%whatever%' AND (id='1' OR id='2' OR id='3')

AND has a higher precedence than OR, so your original was interpreted as:

WHERE )column LIKE '%whatever%' AND id='1') OR id='2' OR id='3'

The original is better written with in:

SELECT *
FROM table
WHERE column LIKE '%whatever%' AND id in ('1', '2', '3')

And, if id is really an integer, you should drop the single quotes. They suggest the type is really a string.

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

Use the IN function

SELECT * FROM table WHERE column LIKE '%whatever%' AND id IN ('1', '2', '3')

I assume id is a varchar. If its an int then use:

SELECT * FROM table WHERE column LIKE '%whatever%' AND id IN (1, 2, 3)
SyntaxGoonoo
  • 900
  • 8
  • 10