Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude records matching subquery

There is probably an obvious answer to this question, but I am having one heck of a time getting anywhere with it.

Consider the query:

SELECT *
FROM reports AS r
JOIN reportvalues AS rv ON rv.report_id = r.report_id
JOIN metrics AS m ON m.metric_id = rv.metric_id
WHERE r.report_id NOT IN(
    SELECT DISTINCT report_id
    FROM exclude_report
)

In this query, exclude_report is a view constructed in a similar manner.

Now what happens is the query takes an EXTREMELY long time to execute, presumably because the subquery is being executed over each and every row in the parent query. However, I am finding no feasible means of doing this any other way.

Oh great SQL wizards, please advise. I really need a way of doing this all in SQL, which I will be using in SSRS.

like image 645
Skudd Avatar asked Nov 15 '25 13:11

Skudd


1 Answers

The distinct is probably killing you, you don't need distinct in a subquery when using in

Is this better?

SELECT *
FROM reports AS r
JOIN reportvalues AS rv ON rv.report_id = r.report_id
JOIN metrics AS m ON m.metric_id = rv.metric_id
WHERE NOT EXISTS (SELECT 1 
        FROM exclude_report e 
        WHERE e.report_id = r.report_id)
like image 100
SQLMenace Avatar answered Nov 17 '25 08:11

SQLMenace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!