我必须在join(SQL Server)中使用条件语句
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 = B.id) or
((B.id is null or B.id = '') and A.id2 = B.id2)
答案 0 :(得分:0)
我认为这不是解决这个问题的最佳方法,但可能很有用,也很简单:
SELECT * FROM a INNER JOIN b
ON a.id = b.id
UNION
SELECT * FROM a INNER JOIN b
ON a.id2 = b.id2
WHERE b.id IS NULL OR b.id = ''
答案 1 :(得分:0)
select * from A inner join B
on (A.id = B.id) OR ((B.id is null or B.id = '') && (A.id2 = B.id2))
答案 2 :(得分:0)
使用CASE
声明
SELECT *
FROM A
INNER JOIN B
ON CASE
WHEN B.id IS NULL OR B.id = '' THEN A.id2
ELSE A.id
END
=
CASE
WHEN B.id IS NULL OR B.id = '' THEN B.id2
ELSE B.id
END
答案 3 :(得分: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