jonnypixel
jonnypixel

Reputation: 327

Mysql query based on a list of specific random numbers?

I'm trying to do a query based on specific numbers which at this stage I only need to hardcode into the page as comma separated values.

2312,2431,2439,2440,2442,....

But I can not use between because the numbers in between may not be relevant

So how do I do a query of this type?

$sql= "SELECT * FROM table 
WHERE pc=2431 OR pc=2439 OR 
      pc=2440 OR pc=2442 OR 
      pc=2443 OR pc=2444 OR 
      pc=2445 OR pc=2446 OR 
      pc=2312 AND v=1 
ORDER BY id DESC 
LIMIT $offset, $rowsperpage";

I tried this and kind of works but there must be a better way.

Thanks in advance

Upvotes: 0

Views: 75

Answers (2)

mkk
mkk

Reputation: 7693

I would suggest a little improvement to other answers:

$pcs = array(2431,2439,2440,2442,2443,2444,2445,2446,2312);

"SELECT *
FROM table
WHERE pc IN (" . implode(",", $pcs) . ")
AND v=1
ORDER BY id DESC
LIMIT $offset"

this way if later your ids will change and you have several queries using them you will have to update only one place instead of N (where N is number of queries). If you use these ids in many different files, consider making a constant

Upvotes: 0

phuzi
phuzi

Reputation: 13060

Indeed there is... You can use the IN operator so that the query becomes:

SELECT *
  FROM table
 WHERE pc IN (2431,2439,2440,2442,2443,2444,2445,2446,2312)
   AND v=1
 ORDER BY id DESC
 LIMIT $offset, $rowsperpage

Simples :o)

For more info check out the MySQL documentation at http://dev.mysql.com/doc/refman/5.5/en/comparison-operators.html#function_in

Upvotes: 1

Related Questions