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
About this post
- Posted
- Archived
- Score
- 18 · 100% up
- Kind
- Text
- ID
- ipdal
52 comments
HELLO FRIEND I HAVE SOLUTION
FAKE.
I real bad developer wouldn't have set size_of_array to 0 before using it.
This is much worse:
whoooosh
What's wrong with /r/PHP? How does this comment have positive karma?
checks username
+1 to you sir.
Totally went over my head too.
Don't worry guys! I made it secure and OOP!
Edit: Added some debugging with $success.
OOP with a good jizzing of procedural code!
This account could be... interesting. By the way, here's one I made earlier.
Use the "IN" method, it'll make you code easier to read and will be more efficient within SQL.
I just needed to use IN the other day, it worked perfectly
Yes, a bit more efficient in SQL than any alternatives.
this !
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.
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.
True. I just was offering a quick and dirty solution using the non-parameterized version :)
...
Be careful about SQL injection, folks
Check $ids before you use it. Make sure they're integers or whatever.
Thats why I added "if the ids arent direct user input"
Deleted before we saved it.
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)
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;Same output. :C
Try benchmarking them.
Same output. :C
Operator
INis a terrible performance hit outside small groups. Generally, you're better off making and joining to a temporary table, with something likeIf you also want to see the rows that weren't matched, switch to a left join.
For what it's worth, questions like these should be in /r/sql.
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
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.
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.
A hell of a lot less inefficient than using operator in.
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.
Use IN, it's the smartest way. $query = 'SELECT * FROM
tableWHEREidIN (' . implode(',', $ids) . ');';In has a terrible performance impact. Prefer to use a join to a temporary table.
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.
Use IN and don't ever use multiple queries if you don't have to.
is significantly slower than IN() on a medium/large dataset and multiple queries even more so.
They're both terribly slow. Compare joining against a virtual table assembled with union, especially as the data grows.
Sorry for reviving and old discussion, could you please show me a simple example?
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.
Would you give some specific details as to which DB's you've had this problem with, and what kind of thresholds?
Sure. Oracle for example has a hard limit of 1000. SQL Server has a soft limit governed by system resources. MySQL has a soft limit governed by packet size.
You can just make a temporary table instead.
http://www.reddit.com/r/PHP/comments/ipdal/best_way_to_select_multiple_separate_ids/c25p8f8
Don't forget to index!
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!
Famous last words. I've said them, I've heard them, I no longer believe them.
'... field IN('.implode(',',$ids).')';
or mongodb:
{_id:[ida.join('.')]}
Do bear in mind that
SELECT ... FROM ... WHERE id IN (SELECT id FROM ... WHERE ...)
Sadly, mysql is horrifically slow at subqueries when the going gets tough. Everyone's advice about IN() is the better answer.
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.