T-SQL > 自连接 > where 子句不起作用
T-SQL > Self Join > where clause not working
这将是我的第一个 post,希望我 post 这个问题足够详细并且足够具体。
首先,我将 table 连接到自身(结构 s1 JOIN 结构 s2)。
这个 table 然后加入另一个 table (planning_entity pe)。
然后我对上面的结果应用了两个过滤器:
pe.short_name = '1024824'
s2.structure_code = s1.father_code
目的是 return 只有 s2.structure_code 和 s1.father_code 的那些行。但是,我下面的查询结果似乎 return s2.structure_code 和 s1.father_code 的所有值。
我的自我加入结构不正确吗?还是我没有正确规定过滤器?
您可能会说,我是 SQL 的新手...非常感谢任何帮助...
SELECT pe.short_name, s2.description, s1.father_code, s2.structure_code
FROM structure s1
INNER JOIN structure s2 ON s1.father_code = s2.structure_code
INNER JOIN planning_entity pe ON s2.structure_code = pe.planning_code
WHERE pe.short_name ='1024824'
AND s2.structure_code = s1.father_code
ORDER BY s2.structure_code
自加入 - 结果
试试这个,您的查询运行良好,只需如下更改 select 列并通过删除 where 子句对其进行改进。
复制查询并检查输出。我希望它会按照你的要求完成,我从你提到的问题中了解到。必须分享您的经验。
SELECT pe.short_name, s1.description, s1.father_code, s2.structure_code
FROM structure s1
INNER JOIN structure s2 ON
s1.father_code = s2.structure_code
INNER JOIN planning_entity pe ON
s2.structure_code = pe.planning_code and
pe.short_name ='1024824'
ORDER BY s2.structure_code
这将是我的第一个 post,希望我 post 这个问题足够详细并且足够具体。
首先,我将 table 连接到自身(结构 s1 JOIN 结构 s2)。
这个 table 然后加入另一个 table (planning_entity pe)。
然后我对上面的结果应用了两个过滤器:
pe.short_name = '1024824'
s2.structure_code = s1.father_code
目的是 return 只有 s2.structure_code 和 s1.father_code 的那些行。但是,我下面的查询结果似乎 return s2.structure_code 和 s1.father_code 的所有值。 我的自我加入结构不正确吗?还是我没有正确规定过滤器?
您可能会说,我是 SQL 的新手...非常感谢任何帮助...
SELECT pe.short_name, s2.description, s1.father_code, s2.structure_code
FROM structure s1
INNER JOIN structure s2 ON s1.father_code = s2.structure_code
INNER JOIN planning_entity pe ON s2.structure_code = pe.planning_code
WHERE pe.short_name ='1024824'
AND s2.structure_code = s1.father_code
ORDER BY s2.structure_code
自加入 - 结果
试试这个,您的查询运行良好,只需如下更改 select 列并通过删除 where 子句对其进行改进。 复制查询并检查输出。我希望它会按照你的要求完成,我从你提到的问题中了解到。必须分享您的经验。
SELECT pe.short_name, s1.description, s1.father_code, s2.structure_code
FROM structure s1
INNER JOIN structure s2 ON
s1.father_code = s2.structure_code
INNER JOIN planning_entity pe ON
s2.structure_code = pe.planning_code and
pe.short_name ='1024824'
ORDER BY s2.structure_code