【问题标题】:Pairing records in table using column and then finding Children records? SQL使用列配对表中的记录,然后查找子记录? SQL
【发布时间】:2013-10-09 13:58:56
【问题描述】:

我正在尝试将祖父母表中的两条或多条记录配对,以便我可以从一个孙子表中找到它的孙子记录。

每个 Product_Maintenance 记录都有一个 Product Parent 记录,每个 Product 记录都是 Product_Group Grandparent 记录的一部分。

如图。

所以我的查询将从今天创建的新创建的孙子 (Product_Maintenace) 记录开始,并将向上遍历层次结构到祖父记录。然后它将找到所有其他的 Grand 孩子,然后将它们加入结果集。

到目前为止,这是我的查询,但问题是它似乎只是复制了一个孙子记录的结果而没有加入其他记录,我认为这是因为我的 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

这会是嵌套选择语句有用的地方吗?

【问题讨论】:

    标签: sql oracle hierarchy


    【解决方案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
    

    【讨论】:

    • 有趣,我第一次查询没有结果。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多