从3个三个表中获取数据,以非空值为准

时间:2019-01-25 05:11:21

标签: sql join null

我正在尝试从三个表中找到可用的地址详细信息。

当表1包含地址详细信息时,请从表1获取地址

如果表1的地址为空,则考虑表2,

如果表2地址为空,则考虑表3,否则显示表1地址(空)

表1中有外键可以用来联接表2和3,但是它们也可以为空,在这种情况下,仅考虑表1中的数据。

在我的查询中,当外键可用时,我可以联接表,但如果它们为空,则该查询不起作用!

我不确定在外键为空的情况下是否可以添加“ Case”语句来忽略“ Join”条件。

有人可以帮忙吗?

enter image description here

我的查询如下:

SELECT donor.donor_num,

CASE

--WHEN donor.addr1 IS NULL THEN paraddress.addr1

--WHEN paraddress.addr1 IS NULL THEN enrparaddr.addr1

WHEN donor.addr1 IS NULL THEN enrparaddr.addr1

ELSE donor.addr1

END AS Address1,

CASE

--WHEN donor.addr2 IS NULL THEN paraddress.addr2

--WHEN paraddress.addr2 IS NULL THEN enrparaddr.addr2

WHEN donor.addr2 IS NULL THEN enrparaddr.addr2

ELSE donor.addr2

END AS Address2

FROM donor

JOIN enrparaddr ON enrparaddr.par_code = donor.enrol_code

--JOIN paraddress ON paraddress.par_code = donor.par_code

WHERE donor_num = '17206' 

请参阅三个表的附件图片

4 个答案:

答案 0 :(得分:0)

您可以尝试以下操作-使用FULL OUTER JOINcoalesce()函数

SELECT donor.donor_num,
       coalesce(donor.addr1,paraddress.addr1,enrparaddr.addr1) AS Address1,
       coalesce(donor.addr2,paraddress.addr2,enrparaddr.addr2) AS Address2
FROM donor
FULL OUTER JOIN enrparaddr ON enrparaddr.par_code = donor.enrol_code
FULL OUTER JOIN paraddress ON paraddress.par_code = donor.par_code
WHERE donor_num = '17206'

答案 1 :(得分:0)

SELECT donor.donor_num,CASE WHEN donor.addr1 IS NULL 
                            THEN enrparaddr.addr1
                            ELSE donor.addr1
                        END AS Address1,
                        CASE WHEN donor.addr2 IS NULL 
                             THEN enrparaddr.addr2
                             ELSE donor.addr2
                        END AS Address2

FROM donor
left join  enrparaddr ON enrparaddr.par_code = donor.enrol_code
WHERE donor_num = '17206' 

答案 2 :(得分:0)

我建议:

SELECT d.donor_num,
       coalesce(d.addr1, pp.addr1, epe.addr1) AS Address1,
       coalesce(d.addr2, pp.addr2, epe.addr2) AS Address2
FROM donor d LEFT JOIN
     paraddress pp
     ON pp.par_code = d.par_code LEFT JOIN
     enrparaddr epe
     ON epe.par_code = d.enrol_code AND
        pp.par_code IS NULL
WHERE d.donor_num = 17206  -- do not use single quotes for numbers

注意:

  • 您想要一个LEFT JOIN,因为您想要donors中的所有行。
  • 您应该按照COALESCE()所使用的顺序连接表。
  • 第二个JOIN条件可以限于第一个条件不匹配的情况。
  • 数字常量不应使用单引号。

答案 3 :(得分:0)

您可以使用简单的Case .. When语句来做到这一点:

Select Case     
When A.ID is NULL And B.ID is NULL And C.ID is NULL Then -- when all columns contain null
    NULL
When A.ID is NULL And B.ID is NULL Then
    C.ID
When B.ID is NULL and C.ID is NULL Then
    A.ID
When A.ID is NULL And C.ID is NULL Then
    B.ID
End As ID
From A, B, C