Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Select statement in MYSQL join

SELECT * FROM A
JOIN B
ON B.ID = A.ID
AND B.Time =   (SELECT max(Time) 
                            FROM B B2
                            WHERE B2.ID = B.ID)

I am trying to join these two tables in MYSQL. Don't pay attention to that if the ID is unique then I wouldn't be trying to do this. I condensed the real solution to paint a simplified picture. I am trying to grab and join the table B on the max date for a certain record. This procedure is getting run by an SSIS package and is saying B2.ID is an unknown column. I do things like this frequently in MSSQL and am new to MYSQL. Anyone have any pointers or ideas?

like image 484
JBone Avatar asked Aug 25 '11 17:08

JBone


People also ask

Can we use SELECT statement in join?

A join is a relational operation in a SELECT statement that retrieves data from two or more tables, based on matching column values. The data in the tables is linked into a single result. Each row of the first table is combined with each row of the second table, keeping only the rows where the join condition is true.

Can we use joins inside a nested query?

A subquery can be used with JOIN operation. In the example below, the subquery actually returns a temporary table which is handled by database server in memory. The temporary table from the subquery is given an alias so that we can refer to it in the outer select statement.

Can subquery join tables?

yes, sql works on sets, a subquery returns a set as result, so this is possible.


1 Answers

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.

like image 104
Bill Karwin Avatar answered Sep 18 '22 15:09

Bill Karwin