如何修改我的SQL以加快速度?

时间:2014-12-19 02:22:58

标签: php mysql

旧的SQL就像这样

SELECT COUNT(*) AS tp_count 
FROM sdb_b2c_orders 
WHERE pay_status='1' 
    and createtime>1413533130 
    and area_code in (1030,1031,1032,1033) 
    and member_id in (
        select member_id 
            from sdb_invite_invite 
            where in_member_id=14273 
                or in_member_id=13742 
                or in_member_id=14299
    ) 
LIMIT 1;

结果是22

但它很慢,我想修改它以使其更快。新的sql是这样的:

SELECT COUNT(*) AS tp_count 
    FROM sdb_b2c_orders AS bo 
        INNER JOIN sdb_invite_invite AS ii ON bo.member_id=ii.in_member_id 
    WHERE bo.pay_status='1' 
        AND bo.area_code IN (1030,1031,1032,1033) 
        AND bo.createtime>1413533130 
        AND ii.in_member_id IN (14273,13742,14299)

但结果是131 ......为什么?

2 个答案:

答案 0 :(得分:0)

我建议你改用exists

SELECT COUNT(*) AS tp_count
FROM sdb_b2c_orders o
WHERE pay_status = '1' and createtime > 1413533130 and area_code in (1030,1031,1032,1033) and
      exists (select 1
              from sdb_invite_invite i
              where i.member_id = o.member_id and i.in_member_id in (14273, 13742, 14299) 
             );

您还可以使用索引提高性能。我建议sdb_b2c_orders(pay_status, createtime, area_code, member_id)sdb_invite_invite(member_id, in_member_id)

答案 1 :(得分:0)

  

SELECT COUNT(*)AS tp_count       来自sdb_b2c_orders AS bo           INNER JOIN sdb_invite_invite AS ii ON bo.member_id = ii.in_member_id       在哪里bo.pay_status ='1'           AND bo.area_code IN(1030,1031,1032,1033)           AND bo.createtime> 1413533130           AND ii.in_member_id IN(14273,13742,14299)

bo.memeber_id=ii.in_member_id修改为bo.member_id=ii.member_id

然后它有效!