caner taşdemir caner taşdemir - 1 year ago 69
MySQL Question

mySQL - Is there a better way of using many OR oparators in query?

I have a huge members database. Let's say I have 10 names.
I need to fetch these members' last seen values from members table in a fastest way. I have tried

SELECT lastseen FROM members WHERE
name='Pierce' OR
name='John' OR
name='Steven' OR
name='James' OR
name='Ernie' OR
name='Stuart' OR
name='Blake' OR
name='Shaun' OR
name='Pat' OR

But using many OR oparators in the query is an unprofessional way and slow, are there better methods ?

Answer Source

Use IN:

SELECT lastseen
FROM members
WHERE name IN ('Pierce', 'John', . . . )

In MySQL, there is even a performance advantage to using IN instead of ORs. MySQL will create a binary tree for searching the values (assuming they are constants), which speeds up the processing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download