【问题标题】:CTE query not returning duplicate rowsCTE 查询不返回重复行
【发布时间】:2016-03-22 19:58:48
【问题描述】:

出于审计目的,我使用触发器将更改插入到审计表中。然后我使用 CTE 递归地获取特定项目的所有审计行。

这个SQLFiddle 添加了一些审计行和我当前正在使用的 CTE。

这是 CTE:

;WITH cteAudit AS
(
    SELECT id, [user_name], date_time, item_parent_type, item_parent_id, 
        item_type, item_id, item_action, row_guid, 1 AS audit_level
    FROM audit
    WHERE 
        (item_type = 22 AND item_id = 925) 
    UNION ALL
    SELECT a.id, a.[user_name], a.date_time, a.item_parent_type, a.item_parent_id, 
          a.item_type, a.item_id, a.item_action, a.row_guid, cteAudit.audit_level + 1
    FROM audit a
        INNER JOIN cteAudit
            ON a.item_parent_id = cteAudit.item_id
            AND a.item_parent_type = cteAudit.item_type
    WHERE 
        a.item_parent_type <> a.item_type AND
        a.item_parent_id <> a.item_id   
)

SELECT
    cteAudit.id,
    cteAudit.[user_name],
    cteAudit.date_time,
    cteAudit.item_parent_id,
    @itemtype AS item_type,
    cteAudit.item_id,
    item_action,
    cteAudit.audit_level,
    CONVERT(nvarchar(36), cteAudit.row_guid) AS row_guid
ORDER BY date_time DESC, audit_level desc

但是,对于这个 CTE,我有 2 个问题:

  1. 查询未返回所有 13 行。它不显示第 11-13 行。这是因为主表(客户)没有经过审核,因为用户只是更改了联系人的地址。

发生这种情况是因为我修改了第 3 级(联系人),并且此级别有一个到第 2 级(联系人列表)的链接。但是第 2 级,它有到第 1 级(客户)的链接,没有被修改,并且因此不在审计表中,因此没有到第一级的链接。

  1. 查询返回重复记录。

如何返回主表的所有行?为什么查询返回重复的行?

【问题讨论】:

    标签: sql sql-server common-table-expression


    【解决方案1】:

    您的问题来自不正确的查询或不正确的数据。

    您向递归查询询问这些约束:

    WHERE 
            a.item_parent_type <> a.item_type AND
             a.item_parent_id <> a.item_id
    

    但对于第 11 - 13 行,item_parent_id 等于 item_id

    你还要求 AND a.item_parent_type = cteAudit.item_type 但是对于第 11 - 13 行,您的类型被翻转,因此不正确。

    【讨论】:

    • 好吧,这取决于您将数据更改为什么,那么它很可能允许一行绑定到自身。如果您也选择了父 id,它会更容易调试
    猜你喜欢
    • 1970-01-01
    • 2016-04-11
    • 2023-03-28
    • 1970-01-01
    • 2016-05-08
    • 2016-07-12
    • 1970-01-01
    • 2018-08-05
    • 1970-01-01
    相关资源
    最近更新 更多