views:

32

answers:

1

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);
A: 

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;
Martin