【问题标题】:Improving SELECT performance in MySQL提高 MySQL 中的 SELECT 性能
【发布时间】:2016-08-25 00:57:52
【问题描述】:

我有这张交易表:

idtransaction(pk)

时间

数量

价格单位

transaction_type(枚举买|卖)

item_iditem(fk)

character_idcharacter(fk)

我正在尝试检索属于给定用户的每个字符的每个买卖交易(用户帐户可以有多个字符),按日期排序。有一个表 '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 上摆弄别的东西)

【问题讨论】:

标签: mysql performance select


【解决方案1】:

首先我会摆脱内部的“ORDER BY character_idcharacter”。如果这对性能没有太大帮助,我建议使用内部联接而不是子查询。像这样的……

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

诺埃尔

【讨论】:

  • 效果很好,从 5 秒缩短到 0.1!非常感谢
  • @jonnybravo,你不喜欢这种改进吗?
【解决方案2】:

你可以试试 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

【讨论】:

    猜你喜欢
    • 2018-09-06
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 1970-01-01
    • 2016-10-07
    相关资源
    最近更新 更多