Reputation: 41605
This query runs slowly:
SELECT UserAccountNumber, balance, username FROM users JOIN balances ON
users.UserAccountNumber=balances.UserAccountNumber WHERE date < “2011-02-02”
What can i do to improve its performance?
I thought about using the user ID for the join instead of the userAccountNumber. Appart form it, as far as i know, the JOIN and WHERE users.id = balances.idUser perform at the same speed...
So.. what else could i change to improve it? Thanks.
Upvotes: 2
Views: 2841
Reputation: 3892
If the tables are huge you might get some improvement using a temporary table rather then letting MySQL's optimiser sort it out for you. It'll be a trade off for sure though.
CREATE TEMPORARY TABLE `tmp_balances`
(
`UserAccountNumber` INT,
`balance` INT,
INDEX (`UserAccountNumber`)
) ENGINE=MEMORY
SELECT `UserAccountNumber`, `balance`
FROM balances
WHERE date < "2011-02-02";
SELECT `tmp_balances`.`UserAccountNumber`,
`tmp_balances`.`balance`,
`users`.`username`
FROM `tmp_balances` INNER JOIN users USING (`UserAccountNumber`);
Other then that (and it's a bit of a long-shot), I'd have to echo what the earlier commentors said about indexing.
Upvotes: 0
Reputation: 34581
The query itself looks OK to me, but make sure you have indexes on the UserAccountNumber
columns (since they're involved in the join) and date
(the column you're searching on). If the database has to do a sequential scan of a lot of records, that'll be slow. Using EXPLAIN SELECT
may help you to understand how the database is actually performing the query.
Upvotes: 4