树SQL查询的孙女

时间:2017-05-23 18:45:04

标签: sql

任何人都可以帮我解决这个特定输出的sql代码:

列出共同定位的树(即tr_loc值相同),并且一棵树是另一棵树的孙女。Table data

这是我提出的,但我确定这是错误的:

SELECT tr_loc a, tr_loc b,  Tr_numb, Tr_forest 
FROM Tree
WHERE a.tr_loc = b.tr_loc 
  AND a.TR_parent = b.Tr_numb;

1 个答案:

答案 0 :(得分:1)

我认为这就是您对查询的要求:

SELECT
a.tr_numb AS granddaughter
,c.tr_numb AS grandfather
,a.tr_loc
,a.Tr_forest

FROM
Tree a, Tree b, Tree c

WHERE
a.tr_parent = b.tr_numb
AND b.tr_parent = c.tr_numb
AND a.tr_forest = c.tr_forest
AND a.tr_loc = c.tr_loc

请注意abc是表格Tree的别名。那是self join。我会在这里留下这个问题,这样你就可以试着看看你哪里出错了。

但是,我不建议使用JOIN的语法。学习更明确的语法要好得多。以下是我编写查询的方法:

SELECT
Tree.Tr_numb AS tree
,Parent.Tr_numb AS parent
,Grandparent.Tr_numb AS grandparent
,Tree.tr_forest
,Tree.tr_loc

FROM
Tree
INNER JOIN Tree [Parent] ON (Parent.Tr_numb = Tree.Tr_parent)
INNER JOIN Tree [Grandparent] ON (Grandparent.Tr_numb = Parent.Tr_parent)

WHERE
Tree.Tr_loc = Grandparent.Tr_loc