简体   繁体   English

改善加入绩效

[英]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. 我考虑过使用用户ID进行联接,而不是使用userAccountNumber。 Appart form it, as far as i know, the JOIN and WHERE users.id = balances.idUser perform at the same speed... 据我所知,Appart形成了JOIN和WHERE users.id = balances.idUser以相同的速度执行...

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). 该查询本身对我来说还可以,但是请确保您在UserAccountNumber列(因为它们参与了联接)和date (您正在搜索的列)上都有索引。 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. 使用EXPLAIN SELECT可以帮助您了解数据库实际上是如何执行查询的。

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. 如果表很大,使用临时表可能会有所改善,而不是让MySQL的优化程序为您解决。 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. 除此之外(这是一个长镜头),我不得不回应早期评论者关于索引的说法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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