Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do select from where x is equal to multiple values?

Tags:

sql

mysql

I am debugging some code and have encountered the following SQL query (simplified version):

SELECT ads.*, location.county  FROM ads LEFT JOIN location ON location.county = ads.county_id WHERE ads.published = 1  AND ads.type = 13 AND ads.county_id = 2 OR ads.county_id = 5 OR ads.county_id = 7 OR ads.county_id = 9 

I'm getting very strange results from the query and I think its because the first OR is negating the AND operators that are found before it.

This results in getting results back for ads of all types and not just for the type 13.

Each time the query is called there may be a differnt amount of county entities that need to be looked up.

Any help on the correct way to go about this would be appreciated.

like image 533
Binarytales Avatar asked Nov 04 '08 12:11

Binarytales


People also ask

How do I SELECT multiple values from the same column in SQL?

Note – Use of IN for matching multiple values i.e. TOYOTA and HONDA in the same column i.e. COMPANY. Syntax: SELECT * FROM TABLE_NAME WHERE COLUMN_NAME IN (MATCHING_VALUE1,MATCHING_VALUE2);

Can WHERE clause have multiple values?

The IN operator allows you to specify multiple values in a WHERE clause. The IN operator is a shorthand for multiple OR conditions.

Can we use multiple WHERE clause in SQL?

You can specify multiple conditions in a single WHERE clause to, say, retrieve rows based on the values in multiple columns. You can use the AND and OR operators to combine two or more conditions into a compound condition. AND, OR, and a third operator, NOT, are logical operators.


1 Answers

Put parentheses around the "OR"s:

SELECT ads.*, location.county  FROM ads LEFT JOIN location ON location.county = ads.county_id WHERE ads.published = 1  AND ads.type = 13 AND (     ads.county_id = 2     OR ads.county_id = 5     OR ads.county_id = 7     OR ads.county_id = 9 ) 

Or even better, use IN:

SELECT ads.*, location.county  FROM ads LEFT JOIN location ON location.county = ads.county_id WHERE ads.published = 1  AND ads.type = 13 AND ads.county_id IN (2, 5, 7, 9) 
like image 180
Greg Avatar answered Sep 24 '22 21:09

Greg