使用列配对表中的记录,然后查找子记录? SQL

时间:2013-10-09 13:58:56

标签: sql oracle hierarchy

我正在尝试在祖父母表中配对两个或更多记录,以便我可以使用一个孙子来找到它的大孩子记录。

每个Product_Maintenance记录都有一个产品记录,每个产品记录都是Product_Group 祖父母记录的一部分。

如图所示。enter image description here

因此,我的查询将从今天制作的新创建的孙(Product_Maintenace)记录开始,并将遍历层次结构到Granparent记录。然后它会找到所有其他的大孩子,然后将它们加入到结果集中。

这是我到目前为止的查询,但问题是它似乎只是复制一个孙子记录的结果而不加入其他记录,我认为这是因为我的WHERE子句将它们过滤掉,因为它们没有创造了今天的日期。

    SELECT product_id, created_date, maintenance_level 
FROM Maintenance maint
    --Traversing Up
    JOIN Products prods
      ON maint.product_id = prods.product_id
    JOIN Groups grps
      ON prods.parent_row_id = grps.row_id
    --Find the linking of Groups
    JOIN Groups link
      ON grps.product_group_id = link.product_group_id
    --Traversing down
    --Now that all linked records are found find all children of those linked grandparents
    JOIN Products prods
      ON prods.par_row_id = link.row_id
    JOIN Maintenance maint
      ON maint.product_id = prods.product_id
WHERE 
    CREATED_DATE = sysdate

这是否会使嵌套的select语句变得有用?

1 个答案:

答案 0 :(得分:1)

我认为最直接的解决方案是让WHERE子句包含相关Product_Group_ID的列表。

SELECT maint.product_id, maint.created_date, maint.maintenance_level 
FROM Maintenance maint
JOIN Products prods ON maint.product_id = prods.product_id
JOIN Groups grps ON prods.parent_row_id = grps.row_id
WHERE grps.Product_Group_ID IN
(   SELECT grps.Product_Group_ID
    FROM Maintenance maint
    JOIN Products prods ON maint.product_id = prods.product_id
    JOIN Groups grps ON prods.parent_row_id = grps.row_id
    WHERE maint.Created_Date = sysdate
)

或者,LEFT JOIN以你的方式向上和向下链接:

SELECT maint2.product_id, maint2.created_date, maint2.maintenance_level 
FROM Maintenance maint1
LEFT JOIN Products prods1 ON maint1.product_id = prods1.product_id
LEFT JOIN Groups grps1 ON prods1.parent_row_id = grps1.row_id
LEFT JOIN Groups grps2 ON grps1.product_group_id = grps2.product_group_id
LEFT JOIN Products prods2 ON prods2.par_row_id = grps2.row_id
LEFT JOIN Maintenance maint2 ON maint2.product_id = prods2.product_id
WHERE maint1.CREATED_DATE = sysdate