如果找不到记录,则忽略WHERE条件

时间:2013-10-24 11:45:47

标签: sql oracle

我写了以下脚本:

SELECT vil.account_id , 
       vil.imp_id, 
       vil.owner ,
       vil.start_date,  
       CASE  
         WHEN ac.status = 4  
         THEN status_date  
         ELSE NULL  
       END AS Live_date,
       cs.country_code  
  FROM ACCOUNT ac  
  INNER JOIN vu_imp_list vil  
     ON vil.account_id = ac.account_id  
  INNER JOIN entity e  
     ON ac.entity_id = e.entity_id  
  INNER JOIN country_specifics cs  
     ON e.country_id = cs.country_id  
WHERE ac.account_id IN
('000206789', '000207464', '000207696', '000207746')  
AND
(vil.start_date =  
(SELECT MIN(vils.start_date)
FROM vu_imp_list vils  
WHERE vil.account_id = vils.account_id) 

这将返回每个imp_id的最早account_id。但是,它会忽略没有imp_id的那些。由于某些account_idsimp_id位置没有vu_imp_list; WHERE's second condition仅会提取具有通讯start_dateimp_id的记录。简而言之,如果在表vu_imp_list中找不到相应的记录,如何忽略这个条件。我发现this post与MySQL相关但看起来有些不对劲,因为我一直收到错误missing SELECT keyword

SELECT vil.account_id , 
       vil.imp_id, 
       vil.owner ,
       vil.start_date,  
       CASE  
         WHEN ac.status = 4  
         THEN status_date  
         ELSE NULL  
       END AS Live_date,
       cs.country_code  
  FROM ACCOUNT ac  
  INNER JOIN vu_imp_list vil  
     ON vil.account_id = ac.account_id  
  INNER JOIN entity e  
     ON ac.entity_id = e.entity_id  
  INNER JOIN country_specifics cs  
     ON e.country_id = cs.country_id  
WHERE ac.account_id IN
('000206789', '000207464', '000207696', '000207746')  
AND
((vil.start_date =  
(SELECT MIN(vils.start_date)
FROM vu_imp_list vils  
WHERE vil.account_id = vils.account_id))  
OR  
NOT EXISTS  
(vil.start_date = (SELECT MIN(vils.start_date)  
FROM obi.vu_implementation_list vils  
WHERE vil.ob10_account_id = vils.ob10_account_id)

1 个答案:

答案 0 :(得分:1)

如果我理解正确的话,你需要LEFT JOIN加入ACCOUNTVU_IMP_LIST并改变WHERE子句中的条件来检查{{1} } {是start_date(找不到NULL中的相应记录)VU_IMP_LIST它等于标量子查询返回的值。使用OR,即使LEFT JOIN表中没有相应的记录,也会返回ACCOUNT表中的所有记录:

VU_IMP_LIST

您可以在此处详细了解不同类型的联接:About SQL Joins