简体   繁体   中英

MS Access: Query taking long time to run

tbcurrent contains 25k rows and tbold contains more than a million rows where it is taking more time run data. Below code is running correctly but looking where I can optimize it to run faster.

(
SELECT
    "Current" as DataFrom,
    a.*
from tbCurrent as a
Inner Join tbOld AS b ON a.Numeric_Inv_No = b.Numeric_Inv_No
    AND a.Amount = b.Amount
    AND a.Vendor_Code <> b.Vendor_Code
Where
    a.Vendor_Code & b.Vendor_Code
    or b.Vendor_Code & a.Vendor_Code in (
    SELECT
        [Vendor A: ID] & [Vendor B: ID] AS MergeB
    FROM tblEXCEPTIONS
    )
UNION ALL
SELECT
    "Old" as DataFrom,
    a1.*
from tbOld as a1
Inner Join tbCurrent AS b1 ON a1.Numeric_Inv_No = b1.Numeric_Inv_No
    AND a1.Amount = b1.Amount   
    AND a1.Vendor_Code <> b1.Vendor_Code
Where
    a1.Vendor_Code & b1.Vendor_Code
    or b1.Vendor_Code & a1.Vendor_Code in (
    SELECT
        [Vendor A: ID] & [Vendor B: ID] AS MergeB
    FROM tblEXCEPTIONS
    )
)
UNION ALL
(
    SELECT
    "Current" as DataFrom,
    a.*
    from tbCurrent as a
    Inner Join tbOld AS b ON a.Numeric_Inv_No = b.Numeric_Inv_No
    AND a.Amount = b.Amount
    AND a.Vendor_Code = b.Vendor_Code
    UNION ALL
    SELECT
    "Old" as DataFrom,
    a1.*
    from tbOld as a1
    Inner Join tbCurrent AS b1 ON a1.Numeric_Inv_No = b1.Numeric_Inv_No
    AND a1.Amount = b1.Amount
    AND a1.Vendor_Code = b1.Vendor_Code
)
ORDER BY
a.Numeric_Inv_No,
DataFrom;

as my comment states. Use a join instead of a where IN()

SELECT
    "Current" as DataFrom,
    a.*
from tbCurrent as a
Inner Join tbOld AS b ON a.Numeric_Inv_No = b.Numeric_Inv_No
    AND a.Amount = b.Amount
    AND a.Vendor_Code <> b.Vendor_Code
inner join tblEXCEPTIONS e on e.[Vendor A: ID] = a.Vendor_Code AND e.[Vendor B: ID] = b.Vendor_Code

When performing multiple SELECT operations like this UNION you can make each part as it's own query. Then make a master query that UNIONS the sub queries. Like this:

(SELECT * FROM QueryFirst
UNION ALL
SELECT * FROM QuerySecond)
UNION ALL
(SELECT * FROM QueryThird
UNION ALL
SELECT * FROM QueryFourth);

This allows you to break the problem down in to smaller chucks that can be evaluated, tested, and optimized independently. This should help you identify duplicate, overlapping, and slow queries. You might find that you don't need so many UNIONS to get the dataset you are looking for.

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