I have a users table with 450,000 records. The table structure is as so:
UserID Int(11) Primary Key
Firstname (50) Varchar
Lastname (50) Varchar
I also need to check two other table to see if the UserID is in those tables. (the structure is a bit different, but the table have the same UserID)
I am running this sub query below, and is running very slow. Appreciate a second set of eyes to offer up a fresh perspective to help run a bit faster…
SELECT
`Users`.`Firstname`,
`Users`.`Lastname`,
`Users`.`UserID`
FROM `Users`
WHERE `Users`.`UserID` IN (SELECT `admin`.`UserID` FROM `admin` WHERE `admin`.`UserID`=`User`.`UserID`)
AND `Users`.`UserID` IN (SELECT `elite`.`UserID` FROM `elite` WHERE `elite`.`UserID`=`Users`.`UserID`)
AND `Users`.`Lastname` LIKE '%smith%'
The absolutely most important thing when optimizing queries in MySQL is to ensure you have the appropriate indexes. Check what indexes you have (using SHOW INDEX), and what indexes the query is using (using EXPLAIN SELECT). Indexes are absolutely vital for good performance once your tables get large.
In particular you should make sure that you have an index on the
UserIDcolumn in all three tables. I’d also suggest adding a foreign key contraint if that is appropriate in your situation.However if you have already checked you have the correct indexes and you still aren’t getting appropriate performance, you can try using joins instead instead of subselects:
Note that
LIKE '%smith%'is unable to use an index efficiently. You should avoid LIKE expressions that start with a wildcard if possible.