Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outer select column value in joined subquery?

Tags:

mysql

Is it possible to use a column value from an outer select within a joined subquery?

SELECT table1.id, table2.cnt
FROM table1 LEFT JOIN (SELECT COUNT(*) as `cnt`
                       FROM table2
                       WHERE table2.lt > table1.lt and table2.rt < table1.rt) AS table2 ON 1;

This results in "Unknown column 'table1.lt' in 'where clause'".

Here is the db dump.

CREATE TABLE IF NOT EXISTS `table1` ( `id` int(1) NOT NULL, `lt` int(1) NOT NULL, `rt` int(4) NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `table2` ( `id` int(1) NOT NULL, `lt` int(1) NOT NULL, `rt` int(4) NOT NULL) ENGINE=MyISAM DEFAULT CHARSET=latin1;

INSERT INTO `table1` (`id`, `lt`, `rt`) VALUES (1, 1, 4);

INSERT INTO `table2` (`id`, `lt`, `rt`) VALUES (2, 2, 3);
like image 617
Michael DePetrillo Avatar asked Apr 21 '10 22:04

Michael DePetrillo


1 Answers

Your inner query is a correlated subquery, but it cannot see table1 at all. This is a restriction on MySQL - see MySQL Manual - D.3. Restrictions on Subqueries. About half way down it states:

Subqueries in the FROM clause cannot be correlated subqueries. They are materialized (executed to produce a result set) before evaluating the outer query, so they cannot be evaluated per row of the outer query.

Although the subquery is part of a LEFT JOIN expression, this is part of the FROM clause.

This reformulation might do the job for you:

SELECT table1.id, 
       (SELECT COUNT(*)
        FROM table2
        WHERE table2.lt > table1.lt
        AND table2.rt < table1.rt) AS cnt
FROM table1;
like image 153
Martin Avatar answered Oct 02 '22 20:10

Martin