返回表中的所有行,并使用新列指示它们是否存在于另一个表中

时间:2014-09-05 18:42:24

标签: sql sql-server tsql stored-procedures join

如果我有两张桌子:

TABLE_SEARCHFIELDS

 FieldID | FieldName
--------------------
 1       | MyField1
 2       | MyField2
 3       | MyField3
 4       | MyField4
 5       | MyField5

TABLE_CUSTOMSEARCHFIELDS

 UserID  | FieldID
--------------------
 1       | 1
 1       | 2
 1       | 5
 2       | 2
 2       | 4
 2       | 5

我希望从第一个表中返回所有Searchfields,但也想表明Searchfield是否对特定用户有效。

E.g。我想查询UserID = 1并获得结果:

 FieldID | FieldName | Active
------------------------------
 1       | MyField1  | 1
 2       | MyField2  | 1
 3       | MyField3  | 0
 4       | MyField4  | 0
 5       | MyField5  | 1

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:4)

我会使用exists执行此操作:

select sf.*,
       (case when exists (select 1
                          from customsearchfields csf
                          where csf.userid = 1 and csf.fieldid = sf.fieldid
                         )
             then 1 else 0
        end) as Active
from searchfields sf;

假设您没有重复的行,您也可以使用left join

执行此操作
select sf.*, (case when csf.userid is not null then 1 else 0 end) as Active
from searchfields sf left join
     customsearchfields csf
     on csf.userid = 1 and csf.fieldid = sf.fieldid;