带有内连接的Oracle case语句

时间:2015-07-14 21:05:33

标签: sql oracle

这是我现在拥有的SQL:

SELECT i.busn_id,
       i.area_name,
       i.date,
       i.area_status,
       i.last_reason_id,
       last_reason.reason_description,
       i.first_reason_id,
       first_reason.reason_description
  FROM busn_info i
       JOIN busn_reason first_reason
         ON( i.first_reason_id = first_reason.reason_id )
       JOIN busn_reason last_reason
         ON( i.last_reason_id = last_reason.reason_id )

此SQL工作正常,但它只返回具有LAST_REASON_ID和FIRST_REASON_ID的行。我想要包含可能只有LAST_REASON_ID或只有FIRST_REASON_ID但不包含任何行的行。

我认为需要在其中构建某种逻辑过程。案件有意义吗?我查看了Stackoverflow和google上的示例,但我需要更多指导。

如果我需要包含更多数据来解释我想要做什么,请告诉我。

3 个答案:

答案 0 :(得分:1)

简化的,自包含的示例(用于创建表的DDL,用于填充几行以重现问题的DML以及预期的输出)总是有用的。您发布的查询将为busn_info表中的每一行返回1行。如果您只想要行first_reason_id is not nulllast_reason_id is not null的行,请将其添加到where子句

 Select BUSN_ID,
        AREA_NAME,
        DATE,
        AREA_STATUS,
        a.last_reason_id,
        (Select B.REASON_description
           FROM BUSN_REASONS B
          WHERE A.LAST_REASON_ID=B.REASON_ID), 
        a.first_reason_id,
        (Select B.REASON_description
           FROM BUSN_REASONS B
          WHERE A.FIRST_REASON_ID = B.REASON_ID)
 FROM BUSN_INFO A
WHERE a.last_reason_id IS NOT NULL
   OR a.first_reason_id IS NOT NULL

这假设一行中没有一行存在NULL值,而不是某些其他标识符,您希望将其解释为"缺少"。

如果您正在使用联接,那么您希望改为使用外部联接并添加相同的WHERE子句

SELECT i.busn_id,
       i.area_name,
       i.date,
       i.area_status,
       i.last_reason_id,
       last_reason.reason_description,
       i.first_reason_id,
       first_reason.reason_description
  FROM busn_info i
       LEFT JOIN busn_reason first_reason
         ON( i.first_reason_id = first_reason.reason_id )
       LEFT JOIN busn_reason last_reason
         ON( i.last_reason_id = last_reason.reason_id )
  WHERE i.last_reason_id IS NOT NULL
     OR i.first_reason_id IS NOT NULL

答案 1 :(得分:0)

如果您至少需要其中一个不为null, 然后添加:

WHERE a.last_reason_id IS NOT NULL OR a.first_reason_id IS NOT NULL

如果您还需要排除指定了两个值的行,请使用

WHERE a.last_reason_id IS NOT NULL AND a.first_reason_id IS NULL  
   OR a.first_reason_id IS NOT NULL AND a.last_reason_id IS NULL

WHERE NOT (a.last_reason_id IS NULL and a.first_reason_id IS NULL)
  AND NOT (a.last_reason_id IS NOT NULL and a.first_reason_id IS NOT NULL)

两种变体产生相同的结果。

答案 2 :(得分:-1)

SELECT busn_id,
       area_name,
       date,
       area_status,
       a.last_reason_id,
       a.first_reason_id,
from   busn_info a
       (
              SELECT reason_description,
                     reason_id
              FROM   busn_reasons ) b
ON a.reason_id=b.reason_id
       (
              SELECT b.reason_description
              FROM   busn_reasons b
              WHERE  a.first_reason_id = b.reason_id )