left join same table twice slow query

时间:2016-03-02 10:52:26

标签: sql left-join

LEFT JOIN (SELECT xx_coinType AS yy_type, xx_sell AS sell_xx
           FROM xxs
           ORDER BY xx_id DESC) AS xxs
               ON xxs.yy_type = zz.zz_coin
LEFT JOIN (SELECT xx_coinType AS yy_type, xx_sell AS old_sell_xx
           FROM xxs
           WHERE xx_time < UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 24 HOUR))
           ORDER BY xx_id DESC) AS old_xxs
               ON old_xxs.coin_type = zz.zz_coin

So I have 2 left joins in my query which select from same table but with a where on one. Since its the same table I select from the query is super slow. How can I fix this?

1 个答案:

答案 0 :(得分:1)

首先,不需要在派生表中使用order by子句 其次,你的第一个派生表只是选择表中的所有记录,所以我不明白它的意义。

试试这个:

LEFT JOIN xxs
               ON xxs.yy_type = zz.zz_coin
LEFT JOIN (SELECT xx_coinType AS yy_type, xx_sell AS old_sell_xx
           FROM xxs
           WHERE xx_time < UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 24 HOUR))
           ) AS old_xxs
               ON old_xxs.coin_type = zz.zz_coin

或者这个:

LEFT JOIN (SELECT xx_coinType AS yy_type, xx_sell AS sell_xx
           FROM xxs
           WHERE xx_time >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 24 
           ) AS xxs
               ON xxs.yy_type = zz.zz_coin
LEFT JOIN (SELECT xx_coinType AS yy_type, xx_sell AS old_sell_xx
           FROM xxs
           WHERE xx_time < UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 24 HOUR))
           ) AS old_xxs
               ON old_xxs.coin_type = zz.zz_coin