user5764534
user5764534

Reputation:

Sql query if is null

I need help to return a result if value exists or no.

UPDATED: The image show where I need help:

Problem SQL

Upvotes: 2

Views: 120

Answers (3)

Thorsten Kettner
Thorsten Kettner

Reputation: 94884

You want a result row for each record in A. So select from A. The data from the other tables can be got with subqueries:

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;

As B:A = 1:n, you can also join B, if you like that better:

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;

Upvotes: 0

sagi
sagi

Reputation: 40481

You can do it using CASE EXPRESSION with a LEFT JOIN .

I didn't fully understand the output you expect, but just add the columns you want:

@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)

Upvotes: 1

Sam
Sam

Reputation: 3155

Use this query:

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

Upvotes: 0

Related Questions