简体   繁体   中英

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.

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 ;

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)

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`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM