Dom
Dom

Reputation: 3080

MySQL corrolated subquery with WHERE clause referencing outer query

I want to join two tables on id columns, where the id is unique in table1, but repeats or may be absent in table2. In table2, I want to use a second column (date) to pick the greatest date which is less than the date corresponding to the date in the table1 row. I need to pick additional columns from table 2.

The query I have is:

SELECT * FROM `t1` LEFT JOIN 
(SELECT `t2`.`other_column`, MAX(`t2`.`date`) FROM `t2` GROUP BY `t2`.`id` WHERE `t2`.`date`<`t1`.`date` )
ON `t1`.`id` = `t2`.`id`

The problem is that you can't use t1 variables in the the WHERE clause of the the t2 subquery.

Upvotes: 1

Views: 85

Answers (3)

Dom
Dom

Reputation: 3080

Turns out that the subquery was a red herring and I could do it all without it.

SELECT `t1`.*, `t2`.*, MAX(`t2`.`date`) FROM `t1` 
LEFT JOIN `t2` 
ON (`t1`.`id`=`t2`.`id` AND `t2`.`date`<`t1`.`date`)
GROUP BY `t1`.`id`

Upvotes: 0

SArnab
SArnab

Reputation: 585

EDIT: Misunderstood question. You will need a subquery in this case.

SELECT * FROM t1 
INNER JOIN 
(
   SELECT id, MAX(t2.date) AS `date` FROM t2 GROUP BY id
) t3 ON (t3.id = t1.id AND t3.date < t1.date)

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1269973

You can do what you want with a correlated subquery in the select clause:

SELECT t1.*
       (SELECT MAX(t2.date)
        FROM t2
        WHERE t2.id = t1.id AND t2.date < t1.date
       ) as t2date
FROM t1 ;

Upvotes: 2

Related Questions