简体   繁体   中英

Improve a Join performance

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM