MySQL Forums
Forum List  »  Newbie

Re: Assistance required for query with subquery
Posted by: Rick James
Date: December 31, 2010 11:56AM

"each unique AddressID is accompanied with lowest OrderID"

First, devise a JOIN to collect the data from the two tables. Then do a GROUP BY and MIN to get the desired result:
SELECT  p.AdresID, MIN(s.OrderID)
    FROM Sync_Orders AS s
    JOIN Sync_Phone  AS p  ON s.PhoneID = p.PhoneID
    GROUP BY p.AdresID

Unfortunately, that will not get you the corresponding Orderdate. That gets trickier...

SELECT AdresID, OrderID, Orderdate
    FROM (
        SELECT  p.AdresID, s.OrderID, s.Orderdate
            FROM Sync_Orders AS s
            JOIN Sync_Phone  AS p  ON s.PhoneID = p.PhoneID
            ORDER BY p.AdresId ASC, s.OrderID ASC   -- Sort the rows so that the MIN is first
         ) x  -- Gather all possible rows
    GROUP BY AdresID   -- This will pick the first row for each AdresId

Options: ReplyQuote


Subject
Written By
Posted
Re: Assistance required for query with subquery
December 31, 2010 11:56AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.