如果我有两张桌子:
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
实现这一目标的最佳方法是什么?
答案 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;