想要使用'not exists'查询正确替换'not in'查询

时间:2018-01-16 07:00:10

标签: sql

我想将此'in'和'not in'查询替换为'exists'和'not exists'查询。

SELECT *
FROM A
WHERE A.key1 NOT IN (
        SELECT key1
        FROM A
        GROUP BY key1
        HAVING COUNT(key1) = 1
        )

UNION

SELECT *
FROM A
WHERE A.key1 IN (
        SELECT key1
        FROM A
        GROUP BY key1
        HAVING COUNT(key1) = 1
        )

我尝试了这个查询,但没用。

SELECT *
FROM A
WHERE NOT EXISTS (
        SELECT 1
        FROM A
        GROUP BY key1
        HAVING COUNT(key1) = 1
        )

UNION

SELECT *
FROM A
WHERE EXISTS (
        SELECT key1
        FROM A
        GROUP BY key1
        HAVING COUNT(key1) = 1
        )

如何更换正确的查询?

2 个答案:

答案 0 :(得分:0)

添加Dim tot As Decimal Try If BREAKDOWNLIST.RowCount <> 1 Then For Each row As DataGridViewRow In BREAKDOWNLIST.Rows If IsNothing(Me.BREAKDOWNLIST.CurrentRow.Cells(5).Value) Then Else If BREAKDOWNLIST.RowCount = 1 Then tot = Val(row.Cells(5).Value) ElseIf BREAKDOWNLIST.RowCount > 1 Then tot += Val(row.Cells(5).Value) End If End If Next ElseIf BREAKDOWNLIST.RowCount = 1 Then End If TOTAL.Text = tot Catch End Try 条件,如下所示,以维护对外部查询的引用

where

答案 1 :(得分:0)

你可以使用它。

SELECT *
FROM A T
WHERE NOT EXISTS (
        SELECT key1
        FROM A
        GROUP BY key1
        HAVING COUNT(key1) = 1
        and MAX(key1) = T.key1
        )
UNION

SELECT *
FROM A T
WHERE EXISTS (
        SELECT key1
        FROM A
        GROUP BY key1
        HAVING COUNT(key1) = 1
        and MAX(key1) = T.key1
        )