0

We have a list of IDs, for example:

11, 22, 55, 99, 187

We have a table with a field "id".

We basically want to select ALL results where the id equals 11, 22, 55, 99, 187

What would be the best way to do a mySQL query like this?

Instead of doing WHEREid= '11' OR '22'.....

We are using this with PHP, as we have a list of IDs and are wanting to select the results using these IDs with a mysql query.

4 Answers 4

3

Use this

Where id IN (11,22,55,99,187)
Sign up to request clarification or add additional context in comments.

Comments

1

try IN clause

Mysql IN clause

Comments

1

As mentioned on other answers you can use the IN (...) clause. But if you have a long list of id values and you want the best performance, then I would suggest using a temporary table to store the values and then use an INNER JOIN on the temporary table:

/* Create the temporary table */
CREATE TEMPORARY TABLE temp_lookup (id INT NOT NULL);
/* Insert values in temp table */
INSERT INTO temp_lookup (id) VALUES (11), (22), (55), (99), (187), ...;
/* Select using INNER JOIN */
SELECT mt.field_list
FROM main_table AS mt INNER JOIN temp_lookup AS tt ON mt.id = tt.id

1 Comment

Did you actually test this or do you have some references? What is the gain? I run a very limited test (4 lookup values/160k records) and saw no gain, actually saw worse performance - 0.12s vs 0.20s. After this I made another test with 33 distinct values in temp_lookup - the difference when to 0.62 for join/temp vs 0.12 with IN. I see no evidence (nor logic) that temp table would work faster. (both test run with no index on id, with indexes both approaches run in 0.0s; with exception that temp table one needs 0.03s to create the temp table)
0

You can use mysql's IN-function

Something like:

SELECT id from table where id IN (11, 22, 55, 99, 187);

It's really logic, just read the manual.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.