不使用IN语句重新设计查询

时间:2019-01-09 09:22:36

标签: mysql sql

我有一个如下查询。该查询工作正常,但是由于我要检查的数据量很大,因此该查询的运行速度较慢。

有人可以帮助我如何优化此查询吗?

SELECT * from trn where concat(comp_id,cus_id) 
IN (select concat(comp_id,cus_id) FROM cus where sid='A0001') 
AND docdate between ('2018-01-01') and ('2018-04-30')

3 个答案:

答案 0 :(得分:5)

concat可能会导致这些性能问题,因为它无法使用索引。

但是MySQL支持多列子查询,因此只需将其删除:

SELECT * from trn 
where (comp_id,cus_id) IN 
        ( select comp_id,cus_id
          FROM cus 
          where sid='A0001'
        ) 
  AND docdate between ('2018-01-01') and ('2018-04-30')

答案 1 :(得分:3)

您可以使用JOIN,例如:

SELECT DISTINCT t.*
FROM trn t 
JOIN cus c ON t.comp_id = c.comp_id AND t.cus_id = c.cus_id
WHERE c.sid='A0001' AND t.docdate BETWEEN ('2018-01-01') AND ('2018-04-30');

答案 2 :(得分:2)

您可以使用EXISTS

SELECT t.*
FROM trn t
WHERE EXISTS (SELECT 1 
              FROM cus c 
              WHERE c.sid = 'A0001' AND c.comp_id = t.comp_id AND c.cus_id = t.cus_id
             ) AND
      docdate between '2018-01-01' and '2018-04-30';