在where语句中处理NULL值(SQL)

时间:2016-08-17 20:13:57

标签: sql null where

所以我查询了以下where语句。基本上,我想确保在过去7天内没有运动或球员活动。

WHERE......   
AND (( (SELECT max(sportswagerbyleague.asOfDate) 
            FROM sportswagerbyleague 
            WHERE sportswagerbyleague.userID = customer_profile.userID)  
                <= date(CURDATE()) - INTERVAL 7 DAY  ) 
                AND ((SELECT max(pa.txndate) 
                    FROM player_activity pa 
                    WHERE pa.userID = customer_profile.userID) <= date(CURDATE()) - INTERVAL 7 DAY ) )

但是,如果存在NULL值(也就是说该用户没有玩家活动或体育活动),那么该特定用户的WHERE语句将变为false。我希望WHERE语句即使对于单个NULL值也保持为true。

建议?

2 个答案:

答案 0 :(得分:1)

将值与NULL值进行比较始终为false,因此您必须单独处理该情况。你可以为此目的使用IS NULL之类的东西。

答案 1 :(得分:0)

转而使用NOT EXISTS来避免三值逻辑:

WHERE......   
AND NOT EXISTS
 ( SELECT *
   FROM sportswagerbyleague 
   WHERE sportswagerbyleague.userID = customer_profile.userID  
     AND sportswagerbyleague.asOfDate > date(CURDATE()) - INTERVAL 7 DAY
 ) 
AND NOT EXISTS
 (
   SELECT *max(pa.txndate) 
   FROM player_activity pa 
   WHERE pa.userID = customer_profile.userID
     AND pa.txndate > date(CURDATE()) - INTERVAL 7 DAY
 )