Mysql EXISTS无法识别上一个表

时间:2016-05-03 07:36:44

标签: mysql subquery

我尝试实现的目标如下,我有一个包含数据的分层表。 每个类别可能有3个子类别(最大)。 所以我想检查从属子类别是否具有子类别(后代),如果他们有产品则检查最后的AND条件。

问题是在最后一个AND条件中无法识别我的ALIAS tree1

/* SQL Error (1054): Unknown column 'tree1.Node_ID' in 'on clause' */

以下是我的查询,我们将不胜感激。

SELECT tree1.Node_ID, tree1.Bez,
IF(EXISTS(SELECT * FROM `301` as tree2 WHERE tree2.Node_Parent_ID <=> tree1.Node_ID LIMIT 1),1,0) as descendants
FROM `301` as tree1
        WHERE tree1.TreeTypNr = 1
        AND tree1.Node_Parent_ID <=> 100001
            AND EXISTS(
                SELECT * FROM `400`
                    INNER JOIN `302` ON `302`.Node_ID = tree1.Node_ID
                        WHERE `400`.GenArtNr = `302`.GenArtNr
                            AND `400`.VknZielNr = 18302
                            AND `400`.VknZielArt = 2
                                LIMIT 1
            )

1 个答案:

答案 0 :(得分:1)

我换了两行:

`400`.GenArtNr = `302`.GenArtNr (put in ON cluase)

`302`.Node_ID = tree1.Node_ID (put in WHERE condition)

试试这个:

SELECT tree1.Node_ID, tree1.Bez,
IF(EXISTS(SELECT * FROM `301` as tree2 WHERE tree2.Node_Parent_ID <=> 
tree1.Node_ID LIMIT 1),1,0) as descendants
FROM `301` as tree1
    WHERE tree1.TreeTypNr = 1
    AND tree1.Node_Parent_ID <=> 100001
        AND EXISTS(
            SELECT * FROM `400`
                INNER JOIN `302` ON `400`.GenArtNr = `302`.GenArtNr
                    WHERE `302`.Node_ID = tree1.Node_ID
                        AND `400`.VknZielNr = 18302
                        AND `400`.VknZielArt = 2
                            LIMIT 1
        )