查询以查找2表中的重复项

时间:2010-12-28 13:40:06

标签: sql ms-access

我有这张桌子

Antecedent           Consequent
I1                   I2                   
I1                   I1,I2,I3
I1                   I4,I1,I3,I4
I1,I2                I1
I1,I2                I1,I4
I1,I2                I1,I3
I1,I4                I3,I2
I1,I2,I3             I1,I4
I1,I3,I4             I4

你可以看到它很乱。 无论如何我可以删除行,如果结果中的项目存在于先行(1行)

例如: INPUT:

Antecedent           Consequent
I1                   I2                   
I1                   I1,I2,I3    <---- DELETE since I1 exist in antecedent
I1                   I4,I1,I3,I4 <---- DELETE since I1 exist in antecedent
I1,I2                I1          <---- DELETE since I1 exist in antecedent
I1,I2                I1,I4       <---- DELETE since I1 exist in antecedent
I1,I2                I1,I3       <---- DELETE since I1 exist in antecedent
I1,I4                I3,I2       
I1,I2,I3             I1,I4       <---- DELETE since I1 exist in antecedent
I1,I3,I4             I4          <---- DELETE since I4 exist in antecedent

输出:

Antecedent           Consequent
I1                   I2  
I1,I4                I3,I2            

无论如何我可以通过查询来做到这一点吗?

2 个答案:

答案 0 :(得分:0)

我看不出如何通过没有用户定义函数的Access查询来完成这项工作,这表明可以更简单地使用VBA删除问题行。

答案 1 :(得分:0)

Rico,每个人都对UDF是对的,用查询做这件事可能会慢一点。 将此功能添加到模块,看看它有多快。我在几秒钟内在500K记录上运行它。

Public Function IsWithin(ByVal vAntecedent As Variant, ByVal vConsequent As Variant) As Boolean
    On Error GoTo ErrQuit
    IsWithin = False
    If Not IsNull(vAntecedent) Then
        If Not IsNull(vConsequent) Then
            Dim aryAnt As Variant, aryCons As Variant
            Dim vAnt  As Variant, vCons  As Variant
            aryAnt = Split(vAntecedent, ",")
            aryCons = Split(vConsequent, ",")
            For Each vAnt In aryAnt
                For Each vCons In aryCons
                    If vAnt = vCons Then
                        IsWithin = True
                        Exit For
                    End If
                Next
                If IsWithin Then Exit For
            Next

        End If
    End If
    Exit Function
ErrQuit:
    IsWithin = False
End Function

您的查询可能如下所示:

SELECT Antecedent, Consequent
FROM Table1
WHERE IsWithin([Antecedent],[Consequent])=False;