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

问题描述 投票:2回答:3

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

任何人都可以帮我如何优化这个查询?

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')
mysql sql
3个回答
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';

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')

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');
© www.soinside.com 2019 - 2024. All rights reserved.