SQL连接语句

时间:2015-04-23 05:58:48

标签: sql sql-server

我必须在join中使用条件语句:

select * from A inner join B
on A.id = B.id

如果B.id is null or B.id = '' or A.id is null or A.id = ''应该是A.name = B.name,而不是A.id = B.id

我必须在join中使用条件语句:

select * from A inner join B
on A.id = B.id

如果B.id is null or B.id = ''它应该是A.id2 = B.id2而不是A.id = B.id

如果我做这样的事情是否正确:

select *
from A inner join B on  
   (B.id is not null and B.id <> '' and A.id is not null and A.id <> '' and A.id = B.id) or 
   ((B.id is null or B.id = '' or A.id is null or A.id = '') and A.name = B.name)

3 个答案:

答案 0 :(得分:0)

我想你会想要这样的东西:

 select * from A
 inner join Bid on  
    (Bid.id is not null and Bid.id <> '' and A.id is not null and A.id <> '' and A.id = Bid.id)
 inner join Bname on 
   ((Bname.id is null or Bname.id = '' or A.id is null or A.id = '') and A.name = Bname.name)

是两次加入B表,一次加入id不为空,第二次加入时id为空并加入{{1}而是列。这与case语句一样有效,因为name表的两个连接是互斥的。

答案 1 :(得分:0)

试试这个

 select * from A inner join B
 on (A.id = B.id) or 
 (A.name = B.name and (B.id is null or B.id = '' or A.id is null or A.id = ''))

答案 2 :(得分:0)

试试这段代码

  DECLARE @b varchar(50)=(SELECT id FROM b)
DECLARE @a varchar(50)=(SELECT id FROM a)
if ((@b in (null , '')) and (@a in (null , '')))

BEGIN

select * from A inner join B
on
A.name = B.name 

END
else

BEGIN

select * from A inner join B
on A.id = B.id 

END