答案 0 :(得分:1)
您可以使用CASE EXPRESSION
使用LEFT JOIN
来执行此操作。
我没有完全理解您期望的输出,只需添加您想要的列:
@in_myvar = 11
select bt.username,at.postid,
CASE WHEN ct.userid is null the 0 else 1 end as c_ind
from A at
INNER JOIN B bt
ON (at.userid = bt.userid and bt.userid = @in_myvar)
LEFT JOIN C ct
ON(ct.userid = at.userid)
答案 1 :(得分:0)
使用此查询:
declare @in_myvar int = 11
select B.username,A.postid,(Case when C.postid = A.postid then 1 Else 0 end) as UserExists
from A inner join B on A.userID = B.UserID
Left Join C
On C.userID = A.userID
where B.userID = @in_myvar
答案 2 :(得分:0)
你想要A中每条记录的结果行。所以从A中选择。其他表中的数据可以通过子查询得到:
select
(select username from b where b.userid = a.userid) as username,
a.postid,
case when exists (select * from c where c.userid = a.userid) then 1 else 0 end as has_c
from a;
如果B:A = 1:n,如果您更喜欢,也可以加入B:
select
b.username,
a.postid,
case when exists (select * from c where c.userid = a.userid) then 1 else 0 end as has_c
from a
join b on b.userid = a.userid;