联盟而不是在一起

时间:2019-02-12 17:24:59

标签: sql-server

SELECT name FROM table1
 WHERE name NOT IN (
    SELECT name, school FROM table2
    UNION
    SELECT name, school FROM table3
 )

此语法使标记“ Union”附近的标记错误保持不变。请问如何解决此问题的任何建议?

2 个答案:

答案 0 :(得分:0)

在子查询中,仅选择用作过滤器的name列。除非您需要nameschool列的组合,否则需要将它们连接起来。除非这是表的实际名称,否则将需要删除table3名称中的空格。如果是这样,它将被括在方括号内,即[table 3]

SELECT name FROM table1
 WHERE name NOT IN (
    SELECT name FROM table2
    UNION
    SELECT name FROM table3
 )

答案 1 :(得分:0)

功能上相同,在某些情况下可能更快

SELECT name 
FROM table1 as t1
left join table2 as t2 on t1.name = t2.name
left join table3 as t3 on t1.name = t3.name
where coalesce(t2.name,t3.name,'new') = 'new'

您还可以使用如下where子句:

where t2.name is null and t3.name is null