简体   繁体   中英

How can I turn this query that uses a join statement into a query that uses a subquery?

I'm given the query

SELECT DISTINCT InvoiceNumber, InvoiceDate, InvoiceTotal
    FROM Invoices JOIN InvoiceLineItems
        ON Invoices.InvoiceID = InvoiceLineItems.InvoiceID
    WHERE InvoiceLineItemAmount > 50
    ORDER BY InvoiceTotal

and told to rewrite it using a subquery. I tried writing

SELECT DISTINCT InvoiceNumber, InvoiceDate, InvoiceTotal
FROM Invoices 
WHERE InvoiceLineItemAmount >  <-----------get error saying the column isn't recognized
    (SELECT InvoiceLineItemAmount
     FROM InvoiceLineItems
     WHERE InvoiceLineItemAmount > 50)
ORDER BY InvoiceTotal

but I get an error saying the column isn't recognized?

You are trying to access sub-query (or inner query) table's column outside and hence the error.

Please try this:

SELECT i.InvoiceNumber, i.InvoiceDate, i.InvoiceTotal
    FROM Invoices i
    WHERE i.InvoiceID in (select InvoiceID from InvoiceLineItems where InvoiceLineItemAmount > 50)
    ORDER BY i.InvoiceTotal

The JOIN is finding a match when there is a line item with an amount greater than 50. That suggests a correlated subquery with EXISTS :

SELECT i.InvoiceNumber, i.InvoiceDate, i.InvoiceTotal
FROM Invoices i
WHERE EXISTS (SELECT 1
              FROM InvoiceLineItems ili
              WHERE ili.InvoiceID = i.InvoiceID AND
                    ili.InvoiceLineItemAmount > 50
             )
ORDER BY i.InvoiceTotal;

Note that SELECT DISTINCT is no longer necessary. With the right indexes, this should be much faster than your original version.

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