Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redesign query without using IN statement

Tags:

sql

mysql

I have a query like below. This query is working fine but since I have huge amount of data to check, this query running is slower.

Can anybody help me how to optimize this query?

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')
like image 385
S S Avatar asked Dec 30 '25 01:12

S S


2 Answers

The concat is probably causing those performance problems as it can't use indexes.

But MySQL supports multi-column subqueries, so simply remove it:

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')
like image 62
dnoeth Avatar answered Jan 01 '26 16:01

dnoeth


You can use JOIN, e.g.:

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');
like image 38
Darshan Mehta Avatar answered Jan 01 '26 17:01

Darshan Mehta