Nested Select statement in MYSQL join

前端 未结 1 1329
遇见更好的自我
遇见更好的自我 2020-12-28 20:14
SELECT * FROM A
JOIN B
ON B.ID = A.ID
AND B.Time =   (SELECT max(Time) 
                            FROM B B2
                            WHERE B2.ID = B.ID)
         


        
相关标签:
1条回答
  • 2020-12-28 20:39

    I do this type of query differently, with an exclusion join instead of a subquery. You want to find the rows of B which have the max Time for a given ID; in other words, where no other row has a greater Time and the same ID.

    SELECT A.*, B.*
    FROM A JOIN B ON B.ID = A.ID
    LEFT OUTER JOIN B AS B2 ON B.ID = B2.ID AND B.Time < B2.Time
    WHERE B2.ID IS NULL
    

    You can also use a derived table, which should perform better than using a correlated subquery.

    SELECT A.*, B.*
    FROM A JOIN B ON B.ID = A.ID
    JOIN (SELECT ID, MAX(Time) AS Time FROM B GROUP BY ID) AS B2
      ON (B.ID, B.Time) = (B2.ID, B2.Time)
    

    P.S.: I've added the greatest-n-per-group tag. This type of SQL question comes up every week on Stack Overflow, so you can follow that tag to see dozens of similar questions and their answers.

    0 讨论(0)
提交回复
热议问题