简体   繁体   中英

How can I replace WHERE IN choices in WHERE clause to reduce execution time of the request?

I am using DBF database in a C++ project written on RAD Studio 10.2 Tokyo. To make request on this database, I am using UniDac Devart component (that is a little bit limited compared to MySQL itself). The problem I have is when using WHERE IN condition in the request, the request makes too much time to be execute (more than one hour sometimes).

This is the request I have :

SELECT accountrp, SUM(amounteur) AS montant FROM %s 
WHERE doctype='1' AND period<>'00' AND
matchno IN(SELECT matchno FROM %s GROUP BY matchno HAVING SUM(amounteur)<>0)
GROUP BY accountrp

accountrp, doctype, period are character and amounteur is numeric.

The problem is around the line matchno IN. I would like to optimize the request without using IN. I saw on Internet that WHERE IN condition can be replaced by INNER JOIN junctions but I Don't know if it is the solution and how to do this.

Can you help me, please ?

You can try with below

SELECT s.accountrp, SUM(s.amounteur) AS montant FROM %s s
  join 
   (SELECT matchno FROM %s GROUP BY matchno HAVING SUM(amounteur)<>0) t
  on s.matchno =t.matchno
WHERE s.doctype='1' AND s.period<>'00'
GROUP BY s.accountrp

A first suggestion you could change the IN clause in a INNER JOIN
this should be more efficent for performance

SELECT accountrp, 
    SUM(amounteur) AS montant 
FROM %s  as s 
INNER JOIN  ( 
  SELECT matchno 
  FROM %s 
  GROUP BY matchno 
  HAVING SUM(amounteur)<>0
) t on t.matchno = s.matchno
WHERE doctype='1' AND period<>'00' AND
GROUP BY accountrp

this because a In clause is equivalent to a set of OR condition and the query is performed each time for each OR .. a inner join instead is just a join between tow table and is performed just one time

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM