【问题标题】:MySQL Correlated Subqueries: Subquery cant find table from outer query?MySQL相关子查询:子查询无法从外部查询中找到表?
【发布时间】:2010-07-28 05:18:58
【问题描述】:

自从我使用相关子查询以来已经有一段时间了,我不确定我这样做是否正确。在我的子查询第二行最后一行中,我试图从外部表中获取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;

【问题讨论】:

    标签: mysql sql mysql-error-1054


    【解决方案1】:

    看来您只需要将表达式从子句 'from' 移动到字段列表

    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;
    

    【讨论】:

    • 将子查询移动到字段列表有效。你的单值表和我的不一样吗?
    • 一模一样!一开始我没听懂你的想法
    • 知道为什么我需要将子查询移动到字段列表吗?我不能从子查询中使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多