MySQL相关子查询:子查询无法从外部查询中查找表?

时间:2010-07-28 05:18:59

标签: mysql sql mysql-error-1054

自从我使用了核心化子查询以来,它已经有一段时间了,我不确定我是否正确行事。在我的子查询第二行,我试图从外表获取node.id。当我尝试执行查询时,我得到了

  

错误代码:1054未知列   'where子句'中的'node.id')

select node.id, node.title, depthLookup.depth
from posts node, (
    select count(parent.title) as depth
    from posts parent, posts children
    where children.lft > parent.lft 
    and children.rgt < parent.rgt
    and children.id = node.id
    order by parent.lft
) as depthLookup;

1 个答案:

答案 0 :(得分:2)

您似乎只需要将表达式从子句'从'移动到字段列表

select node.id, node.title, 
(
    select count(parent.title) as depth
    from posts parent, posts children
    where children.lft > parent.lft 
    and children.rgt < parent.rgt
    and children.id = node.id
    order by parent.lft
) as depthLookup
from posts node;

或使用单值表,如:

select node.id, node.title, depthLookup.depth
from posts node,
(
    select count(parent.title) as depth
    from posts parent, posts children
    where children.lft > parent.lft 
    and children.rgt < parent.rgt
    and children.id = node.id
    order by parent.lft
) as depthLookup;