是否可以使用连接子查询中外部选择的列值?
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;
Run Code Online (Sandbox Code Playgroud)
这导致'where子句'中的"未知列'table1.lt'".
这是db转储.
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);
Run Code Online (Sandbox Code Playgroud)
Mar*_*tin 15
您的内部查询是一个相关的子查询,但它根本看不到table1.这是对MySQL的限制 - 请参阅MySQL手册 - D.3.子查询的限制.大约一半的时间表明:
FROM子句中的子查询不能是相关子查询.它们在评估外部查询之前已实现(执行以生成结果集),因此无法对外部查询的每一行进行求值.
虽然子查询是LEFT JOIN表达式的一部分,但它是FROM子句的一部分.
这种重新制定可能会为您完成这项工作:
SELECT table1.id,
(SELECT COUNT(*) FROM table2 where table2.lt > table1.lt and table2.rt < table1.rt) as cnt
FROM table1;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13424 次 |
| 最近记录: |