2

I have list of items (separated by comma) that I need to look up in a database. Initially I was looking up each item code individually, but there must be an easier way of doing it.

I was playing around in phpMyAdmin trying to select items with no luck.

SELECT * 
FROM  `items` 
WHERE  `code` = ( 20298622
OR 83843296 
OR 46549947 ) 

Returned no results.

SELECT * 
FROM  `items` 
WHERE  `code` =20298622
OR 83843296 
OR 46549947 

Returned every item in the database.

I was reading up on the MySQL docs, and it appears that OR (or ||) should do what I'm looking for. Where did I go wrong?

Also, FWIW, code is a integer field.

Thanks!

0

3 Answers 3

4

You could use...

SELECT * 
  FROM `items` 
 WHERE `code`
    IN (20298622,
        83843296, 
        46549947)
Sign up to request clarification or add additional context in comments.

1 Comment

This is the most convenient answer since all of the items are already separated by a comma. Thanks!
2

The reason it failed is because the OR statement separates two conditional statements. Therefore, your first conditional statement would evaluate (code = 20298622) but then your next statement is simply a number. If you want to use the OR statement, you will need to specify the column name again. Here is what it would look like:

SELECT * 
FROM  `items` 
WHERE  `code` = 20298622
OR `code` = 83843296 
OR `code` = 46549947 

You could also use more complex statements like IN or you could even do a join to a second table (even a temp table). Basically, there are a lot of ways to accomplish this. You will just need to choose which one fits your situation best (speed, ease of use, etc.)

Comments

1

You are not using the correct syntax. You should change the statement to:

SELECT * 
FROM `items` 
WHERE `code` = 20298622
    OR `code` = 83843296 
    OR `code` = 46549947

Or as @alex notes on his answer, you can use the IN clause:

SELECT *
FROM `items` 
WHERE `code` IN (20298622, 83843296, 46549947)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.