Sql查询if为null

时间:2016-06-09 06:36:40

标签: sql

如果值存在或没有,我需要帮助才能返回结果。

更新:图片显示我需要帮助的位置:

Problem SQL

3 个答案:

答案 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;