Skip to content

Best way to select multiple separate IDs

Hey,

does anyone have any insight on what would be the smartest way to select multiple different IDs froma database? Lets say the IDs I have are as an array in PHP instead of stored in a separate table.

So I'd have something like:

$ids = array(4, 56, 67, 87, 142, 842, 900);

and I'd want to select the information related to rows with those IDs in a table. Should I just do where ID = 4 OR ID = 56 OR ID = 67... or mabye where ID IN (4,56,67...) ? Or is it better to just run separate queries for each of the IDs?

** thanks for the answers guys! **

EDIT: there will probably be just 1-10 IDs

18 points51 comments
Open on Reddit
About this post
Posted
Archived
Score
18 · 100% up
Kind
Text
ID
ipdal

Author

8
posts
35
comments
3
media
View profile

52 comments

HELLO FRIEND I HAVE SOLUTION

$size_of_array = 0;
foreach($ids as $id){
    $size_of_array = $size_of_array + $size_of_array;
}

$i = 0;
$results = array();
while($i < $size_of_array){
    $id = $ids[$i];
    $result = mysql_query("select * from table where id = '$id'") or die("MYSQL ERROR");
    array_push($results,$result);
    $i++;
}

foreach($results as $result){
    while($row = mysql_fetch_array($result)){
          echo $row['name'];
    }
}
43 points

FAKE.

I real bad developer wouldn't have set size_of_array to 0 before using it.

13 points

This is much worse:

$size_of_array = $size_of_array + $size_of_array;
8 points

Don't worry guys! I made it secure and OOP!

class MySQLResults {
function get_results() {
$sizeOfArray = $this->sizeOfArray($this->ids);
while($i<$sizeOfArray){
$id=$this->ids[$i];
$result=mysql_query("select * from table where id = '$id'") or die("MYSQL ERROR");
array_push($results,$result);
$i=$i+1;
}
}

function printResults($results) {
while($row = mysql_fetch_array($result)){
# The field name is name
echo $row['name'];
}    
// Return true to let everyone know this worked right.
return true;    
}

function sizeOfArray($array) {
foreach($array as $item) { $size_of_array = $size_of_array + 1; }
return $size_of_array;
}
}

$results = new MySQLResults;
$results->ids = array(1,2,3,4,);
$success = $results->printResults($results->get_results());
if(!$success) echo 'There was an error.';

Edit: Added some debugging with $success.

4 points

If You aren't using parameterized queries and the ids aren't direct user input then You could do something like this:

$query = "select * from mytable where id in (" . implode(',', $ids) . ")";

Definitely better than separate queries as you only need one connection to the database.

7 points

You can do it with parameterized queries too, it just takes a bit more effort as you have to insert a question mark for each value and then add the ids to the parameter collection.

1 points

True. I just was offering a quick and dirty solution using the non-parameterized version :)

1 points
unknown author

...

$ids = array_map('intval', $ids);
// Then implode() as normal
1 points

Be careful about SQL injection, folks

Check $ids before you use it. Make sure they're integers or whatever.

1 points
unknown author

Deleted before we saved it.

1 points

Try running the following queries and attempt to analyze the difference

EXPLAIN SELECT .... FROM ... WHERE ID = 4 OR ID = 56 OR ID = 67...

EXPLAIN SELECT .... FROM ... WHERE ID IN (4, 56, 67, 87, 142, 842, 900)

5 points

After that, try increasing the size of the id list, using a large bulk of generated data to filter against, and add a third strategy: select ... join (select 4 as id union select 56 union select 67) as tempT on foo.id = tempT.id;

3 points

Operator IN is a terrible performance hit outside small groups. Generally, you're better off making and joining to a temporary table, with something like

mysql> create table foo (id integer, label varchar(50));
Query OK, 0 rows affected (0.14 sec)

mysql> insert into foo(id,label) values (3,'noshow 1'), (4,'show 1'), (5,'noshow 2'), 
       (56, 'show 2'), (57, 'noshow 3'), (67, 'show 3');
Query OK, 6 rows affected (0.07 sec)
Records: 6  Duplicates: 0  Warnings: 0

mysql> select * from foo right join 
           (select 4 as matchid union select 56 union select 67) as vbar 
       on foo.id = vbar.matchid;
+------+--------+---------+
| id   | label  | matchid |
+------+--------+---------+
|    4 | show 1 |       4 |
|   56 | show 2 |      56 |
|   67 | show 3 |      67 |
+------+--------+---------+
3 rows in set (0.00 sec)

If you also want to see the rows that weren't matched, switch to a left join.

mysql> select * from foo left join 
           (select 4 as matchid union select 56 union select 67) as vbar 
       on foo.id = vbar.matchid;
+------+----------+---------+
| id   | label    | matchid |
+------+----------+---------+
|    3 | noshow 1 |    NULL |
|    4 | show 1   |       4 |
|    5 | noshow 2 |    NULL |
|   56 | show 2   |      56 |
|   57 | noshow 3 |    NULL |
|   67 | show 3   |      67 |
+------+----------+---------+
6 rows in set (0.04 sec)

For what it's worth, questions like these should be in /r/sql.

5 points

Thanks. I thoguht about placing this in sql, but I figured since i'm workign with php, there might be a clever solution using PDO or something.

If i don't have the values in a temporary table, it probably wouldn't be efficient to create it on the fly with php? I'll look into that "union select X", I'm not familiar with the union operator

0 points

PDO is basically a garbage stack. The reason people like it is that once they've got PDO, they think they have an efficient portable gateway to all SQL which is magically fast. Even if you show them benchmarks, or point out critical basic speed things like bulk insert, they'll just throw a tantrum, insist you're wrong, and downvote you.

If i don't have the values in a temporary table

You're guaranteed not to, since temporary tables are cleaned up after every query. The query I gave you makes the temporary table. That's what the subselect full of unions does.

select 'it' as example union select 'works' union select 'like' union select 'this';

it probably wouldn't be efficient to create it on the fly

A hell of a lot less inefficient than using operator in.

create it on the fly with php?

You seem to be deeply confused. When you're writing something in a query, you're doing it in SQL; it's never anything more than a string to PHP. When you're doing something in PDO, you're doing it half-and-half in the PHP: PDO will fetch generic results then filter and sort them clientside in many cases.

No matter what you do, if the join data isn't already in the database, then you are paying at a minimum the cost of putting it together as a string (the query) at the PHP side and parsing said string at the database side. Nothing will change that. PDO isn't magical. The only way to not pay that expense is to already have the match list at the database's side as data.

Stop trying to psychically predict, on grounds of where you think it is, what will be efficient. Your internal compass is not yet sufficiently strong. Write the query both ways, and benchmark it at a range of data sizes.

Before that, you're really just guessing.

1 points

Use IN, it's the smartest way. $query = 'SELECT * FROM table WHERE id IN (' . implode(',', $ids) . ');';

2 points

In has a terrible performance impact. Prefer to use a join to a temporary table.

1 points

I agree. But performance in many cases is not an issue. Especially if you cache most of your data results. Which you should most of the time.

The op asked for the 'smartest' way. What did he mean exactly? I believe the smartest way is about writing clean and maintainable code and keeping things simple.

1 points

Use IN and don't ever use multiple queries if you don't have to.

2 points

where ID = 4 OR ID = 56 OR ID = 67...

is significantly slower than IN() on a medium/large dataset and multiple queries even more so.

1 points

They're both terribly slow. Compare joining against a virtual table assembled with union, especially as the data grows.

2 points

Use IN but do realize that different db engines have different limitations of how many constants can be listed within an IN statement. And performance can degrade exponentially if you go too high. So if you start seeing a huge performance hit, it's time to load your values into a table and do a IN (SELECT) or an EXISTS.

1 points

Thank you for this! I just wrote a page where I needed a very specific set of results for a select box. This is great!

1 points

EDIT: there will probably be just 1-10 IDs

Famous last words. I've said them, I've heard them, I no longer believe them.

1 points

'... field IN('.implode(',',$ids).')';

or mongodb:

{_id:[ida.join('.')]}

-1 points

Do bear in mind that

SELECT ... FROM ... WHERE id IN (SELECT id FROM ... WHERE ...)

-5 points

Sadly, mysql is horrifically slow at subqueries when the going gets tough. Everyone's advice about IN() is the better answer.

3 points

MySQL is historically crap at everything. That's nothing new. If you want decent performance, you have a crapload of finetuning to do anyway, and at certain complexity MySQL begins to suck so much I'd rather go w/PostgreSQL anyway.

-6 points

Keyboard shortcuts

Move and act

jork
Next / previous post or comment
Enteroro
Open the post
f
Open the media viewer
s
Save
h
Hide (the toast has Undo)
Tab
Right after an action: the toast's Undo
x
Collapse the comment
v
Next layout: cards, compact, grid

Go to

/
Search
gthenh
Home
gthena
All
gthens
Subreddits
gthenl
Library
?
This list
Esc
Close a menu or this list

In the viewer

←or→
Previous / next file
↑or↓
Previous / next post
korj
Previous / next post
Space
Play / pause
m
Mute
z
Zoom
s
Save
o
Open the post (on its own page: back to it)
Esc
Close

Keys do nothing while you type in a box.