views:

93

answers:

7

I'm trying to grab content where id = 3 OR id = 9 OR id = 100... Keep in mind, I can have a few hundred of these ids.

What is the most efficient way to write my query?

$sql = "SELECT name FROM artists WHERE (id=3 OR id=9 OR .... id-100)"
+8  A: 
  ....
WHERE id IN (3, 9, 100, ...)
Ignacio Vazquez-Abrams
At some point it'd probably be easier to insert the ids into a temporary table and do a join on that. But of course that'd require testing to find out just how many ids would make the table creation overhead worth it.
Marc B
A: 

$sql = "SELECT name FROM artists WHERE id REGEXP regex-pattern"

HKVN
-1... inefficient if an index exists and assumes the regex pattern can be more efficient (like ranges), which is not a given (i.e. not in the post).
TomTom
+4  A: 
SELECT * FROM table WHERE id IN (1, 2, 3 etc)

And call only the columns you need rather than using *!

+7  A: 

You may want to use the IN() function:

... WHERE id IN (3, 9, 100);

The IN() function syntax:

expr IN (value,...)

Check whether a value is within a set of values ...

Returns 1 if expr is equal to any of the values in the IN list, else returns 0.

Daniel Vassallo
+3  A: 

You can use SQL IN condition

SELECT * FROM table WHERE ID IN ('1', '2', '3', '4');
Waleed Al-Balooshi
+1  A: 
SELECT * FROM table WHERE id IN (1,2,5);
abatishchev
+2  A: 
SELECT * FROM table WHERE id IN (1,2,5)
Darin Dimitrov
this don't work with []
TooAngel
According to the documentation it does work (http://dev.mysql.com/doc/refman/5.1/en/comparison-operators.html#function_in)
Darin Dimitrov
@TooAngel: `;` will help
abatishchev
Am I messed it up, or had your query [] instead of ()??
TooAngel