我有两张表SurrogateKeys和SurrogateKeyRelatives。
我会发现有些记录可以满足连接两个表的查询。
我正在玩两种选择:
select count(*) from
(
select top(1) sk.Username from SurrogateKeys as sk
inner join SurrogateKeyRelatives as skr
on sk.Id = skr.SurrKeyId
where
sk.Username='John.Doe' and
skr.SomeField = 1
)
和
if exists(
select top(1) sk.Username from SurrogateKeys as sk
inner join SurrogateKeyRelatives as skr
on sk.Id = skr.SurrKeyId
where
sk.Username='John.Doe' and
skr.SomeField = 1
)
begin
select 1
end
else
begin
select 0
end
尝试选项1会在')附近给出错误的语法。我在上面的查询中缺少什么?
答案 0 :(得分:2)
select count(*) from
(
select top(1) sk.Username from SurrogateKeys as sk
inner join SurrogateKeyRelatives as skr
on sk.Id = skr.SurrKeyId
where
sk.Username='John.Doe' and
skr.SomeField = 1
) Q1
答案 1 :(得分:1)
select top(1)
CASE
WHEN skr.SurrKeyId is null THEN 0
ELSE 1
END
from SurrogateKeys as sk
left join SurrogateKeyRelatives as skr
on sk.Id = skr.SurrKeyId
and sk.Username='John.Doe'
and skr.SomeField = 1
答案 2 :(得分:0)
尝试在大括号
之后给内部查询一个表名select count(*) from
(
select top(1) sk.Username from SurrogateKeys as sk
inner join SurrogateKeyRelatives as skr
on sk.Id = skr.SurrKeyId
where
sk.Username='John.Doe' and
skr.SomeField = 1
) table1