我正在调整存储过程。存储过程正在执行SELECT并且具有大约50个WHERE条件。 SQL类似于下面的内容。如果有更好的方法来检查这些条件,你能告诉我吗
SELECT * FROM table A
JOIN table B
ON A.ID = B.ID
WHERE
(
(
A.name = 'abc'
and B.AID not in ( 111, 222)
)
or
(A.name = 'def'
and B.AID not in ( 222,1113,111,654,199,43,243,643,754244,2434)
)
or
(
A.name = 'etd'
and B.AID not in ( 111,345,54,34,454)
)
or
(
A.name = 'ent'
and B.AID not in ( 111,188,199,1647,128006)
)
or
(
A.name = 'yyy'
and B.AID not in (111,188,1113,1647)
)
or
(
A.name = 'uuu'
and B.AID not in (111,188,1113,1647)
)
or
(
A.name = 'jyf'
and B.AID not in (111,188,1647,344,45444,645)
)
or
(
A.name = 'tut'
and B.AID not in (111,222,1113,1647)
)
)
答案 0 :(得分:1)
创建一个表来映射名称和ID:
Name AID
------ ------
abc 111
abc 222
def 222
def 1113
..etc
使用LEFT联接排除匹配项:
SELECT * FROM table A
JOIN table B
ON A.ID = B.ID
LEFT JOIN Exclusions e
ON A.name = e.name
and B.AID = e.AID
WHERE e.name IS NULL -- not in exclusion table
或NOT EXISTS:
SELECT * FROM table A
JOIN table B
ON A.ID = B.ID
WHERE NOT EXISTS(
SELECT null FROM Exclusions e
WHERE A.name = e.name
and B.AID = e.AID
)