是否有更好的方式编写以下查询,以最大程度地减少WHERE语句中的代码重复?
SELECT TA.*
FROM TA
JOIN TB on TA.id = TB.id
JOIN TC on TB.id =TC.id
JOIN TD on TC.id = TD.id
JOIN TE on TD.id = TE.id
WHERE
TC.Name NOT IN (‘John’,’William’,’Jacob’,’Henry’,’David’)
AND TD.Name NOT IN (‘John’,’William’,’Jacob’,’Henry’,’David’)
AND TE.Name NOT IN (‘John’,’William’,’Jacob’,’Henry’,’David’)
-注意:过滤器始终相同:NOT IN(“约翰”,“威廉”,“雅各布”,“亨利”,“大卫”)
答案 0 :(得分:1)
将exists
与table value constructor结合使用,您可以执行以下操作:
SELECT TA.*
FROM TA
JOIN TB on TA.id = TB.id
JOIN TC on TB.id =TC.id
JOIN TD on TC.id = TD.id
JOIN TE on TD.id = TE.id
WHERE NOT EXISTS (
SELECT 1
FROM (VALUES('John'),('William'),('Jacob'),('Henry'),('David')) V(name)
WHERE Name IN(TC.Name, TD.Name, TE.Name)
)