Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner joining to a select statement where the inner select statement's where clause references the outer select?

This is a slimmed down query of my greater problem, but the gist is that I'm trying to inner join to a select where the select is limited by the outer select. Is that possible? I'm getting an error about multipart identifier S.Item and S.SerialNum on the inner select.

The gist is this, we have to group by the item/serial, and the query is big enough, we don't want to go back and group everything in the entire query for this minor join.

SELECT S.Item, S.SerialNum, S.ReceiveDate
    FROM SALES S
    INNER JOIN (SELECT W.Item, W.SerialNum, MIN(W.SalesDate)
                    FROM WARRANTY W
                    WHERE W.Item        = S.Item    AND
                          W.SerialNum   = S.SerialNum
                    GROUP BY Item, SerialNum, SalesDate) WW
        ON S.Item = WW.Item AND WW.SerialNum
like image 361
Alex Kwitny Avatar asked Aug 22 '12 16:08

Alex Kwitny


1 Answers

Looks like you have your JOIN reference in the wrong place.

SELECT S.Item, S.SerialNum, S.ReceiveDate
FROM SALES S
INNER JOIN 
(
    SELECT W.Item, W.SerialNum, MIN(W.SalesDate) MinSalesDate
    FROM WARRANTY W
    GROUP BY Item, SerialNum
) WW
        ON S.Item = WW.Item 
       AND S.SerialNum = WW.SerialNum

Edit, based on your comment about filtering, you can place a WHERE clause on your inner SELECT:

SELECT S.Item, S.SerialNum, S.ReceiveDate, WW.MinSalesDate
FROM SALES S
INNER JOIN 
(
    SELECT W.Item, W.SerialNum, MIN(W.SalesDate) MinSalesDate
    FROM WARRANTY W
    WHERE yourFilter here
    GROUP BY Item, SerialNum
) WW
        ON S.Item = WW.Item 
       AND S.SerialNum = WW.SerialNum
like image 166
Taryn Avatar answered Oct 02 '22 14:10

Taryn