如何检查字段是null还是空mysql?

时间:2013-07-24 11:38:27

标签: mysql sql

我试图弄清楚如何检查字段是空还是空。我有这个

SELECT IFNULL(field1, 'empty') as field1 from tablename

我需要添加额外的支票field1 != "",例如

SELECT IFNULL(field1, 'empty') OR field1 != ""  as field1 from tablename

知道怎么做到这一点吗?

8 个答案:

答案 0 :(得分:156)

使用

SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1 
from tablename

SELECT case when field1 IS NULL or field1 = ''
            then 'empty'
            else field1
       end as field1 
from tablename

如果您只想检查null而不是空字符串,那么您也可以使用ifnull()coalesce(field1, 'empty')。但这不适合空字符串。

答案 1 :(得分:11)

或者您也可以使用CASE

SELECT CASE WHEN field1 IS NULL OR field1 = '' 
       THEN 'empty' 
       ELSE field1 END AS field1
FROM tablename.

答案 2 :(得分:11)

尝试使用nullif

SELECT ifnull(nullif(field1,''),'empty') AS field1
  FROM tablename;

答案 3 :(得分:4)

您可以在IF内使用the IFNULL function。这将会更短,并且字段名称的重复次数会减少。

SELECT IF(IFNULL(field1, '') = '', 'empty', field1) AS field1 
FROM tablename

答案 4 :(得分:3)

您可以创建一个功能来简化这一过程。

create function IFEMPTY(s text, defaultValue text)
returns text deterministic
return if(s is null or s = '', defaultValue, s);

使用:

SELECT IFEMPTY(field1, 'empty') as field1 
from tablename

答案 5 :(得分:0)

如果您想签入PHP,那么您应该执行以下操作:

$query_s =mysql_query("SELECT YOURROWNAME from `YOURTABLENAME` where name = $name");
$ertom=mysql_fetch_array($query_s);
if ('' !== $ertom['YOURROWNAME']) {
  //do your action
  echo "It was filled";
} else { 
  echo "it was empty!";
}

答案 6 :(得分:0)

SELECT * FROM ( 
    SELECT  2 AS RTYPE,V.ID AS VTYPE, DATE_FORMAT(ENTDT, ''%d-%m-%Y'')  AS ENTDT,V.NAME AS VOUCHERTYPE,VOUCHERNO,ROUND(IF((DR_CR)>0,(DR_CR),0),0) AS DR ,ROUND(IF((DR_CR)<0,(DR_CR)*-1,0),2) AS CR ,ROUND((dr_cr),2) AS BALAMT, IF(d.narr IS NULL OR d.narr='''',t.narration,d.narr) AS NARRATION 
    FROM trans_m AS t JOIN trans_dtl AS d ON(t.ID=d.TRANSID)
    JOIN acc_head L ON(D.ACC_ID=L.ID) 
    JOIN VOUCHERTYPE_M AS V ON(T.VOUCHERTYPE=V.ID)  
    WHERE T.CMPID=',COMPANYID,' AND  d.ACC_ID=',LEDGERID ,' AND t.entdt>=''',FROMDATE ,''' AND t.entdt<=''',TODATE ,''' ',VTYPE,'
    ORDER BY CAST(ENTDT AS DATE)) AS ta

答案 7 :(得分:0)

通过修剪和比较,我们确保我们还处理字段中的空白、制表符或空格字符内容。

SELECT
    CASE
        WHEN LTRIM(RTRIM(col_1))='' or col_1 IS NULL THEN 'Not available'
        ELSE col_1
    END AS col_alias
FROM
    my_table