提高MySQL中的SELECT性能

时间:2016-04-29 18:50:42

标签: mysql performance select

我的这张表有交易:

  

idtransaction(PK)

     

时间

     

     

价格单位

     

transaction_type(enum buy | sell)

     

item_iditem(FK)

     

character_idcharacter(FK)

我试图检索属于给定用户的每个字符的每个买卖交易(用户帐户可以有多个字符),按日期排序。有一个表'aggr'列出了每个用户的每个字符,比如

'AGGR' character_idcharacter(fk),user_iduser(fk)

很自然地,我的查询将是(在检索所有销售的情况下)

SELECT idtransaction, item_iditem, quantity, time, price_unit
FROM transaction
WHERE transaction_type =  'Sell'
AND character_idcharacter
IN (

SELECT character_idcharacter
FROM aggr
WHERE user_iduser = ( 
SELECT iduser
FROM user
WHERE username =  'testuser' ) 
ORDER BY character_idcharacter
)
ORDER BY time ASC 

当我总共有大约200万笔交易时,这需要很长时间才能完成(大约700个结果需要4-5秒)。

我已经尝试为字符外键和transaction_type字段创建索引,但似乎没有太大改进。关于如何让它更快的任何提示? (要么重写查询,要么在MySQL上摆弄其他东西)

2 个答案:

答案 0 :(得分:1)

你可以尝试使用INNER JOINS而不是IN来查看它是否更快

SELECT t.idtransaction,t.item_iditem,t.quantity,t.time,t.price_unit
FROM transaction t
INNER JOIN aggr a ON a.character_idcharacter = t.character_idcharacter
INNER JOIN user u ON u.iduser = a.user_iduser
WHERE u.username = 'testuser'
AND t.transaction_type = 'Sell'
ORDER BY t.time ASC

答案 1 :(得分:1)

首先,我将摆脱内部" ORDER BY character_idcharacter"。如果这对性能没有太大作用,我会建议使用内连接而不是subquerys。像这样......

SELECT transaction.idtransaction, transaction.item_iditem, transaction.quantity, transaction.time, transaction.price_unit
FROM transaction INNER JOIN aggr on transaction.character_idcharacter = aggr.character_idcharacter
INNER JOIN user on aggr.user_iduser = user.iduser 
WHERE transaction.transaction_type = 'Sell'
 and user.username = 'testuser' 
ORDER BY transaction.time ASC

诺尔