如何在MySQL中检查字段是否为null或空?

gzszwxb4  于 2023-02-03  发布在  Mysql
关注(0)|答案(8)|浏览(142)

我试图弄清楚如何检查一个字段是NULL还是 empty

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

我需要添加一个额外的检查field1 != "",如下所示:

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

你知道怎么做吗?

6rqinv9w

6rqinv9w1#

任一用途

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'),但是这不适合空字符串。

pgx2nnw8

pgx2nnw82#

使用nullif就可以达到这个目的:

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

工作原理:如果field是空字符串,nullif返回NULL,否则返回字段本身。这两种情况都包括(field为NULL的情况和field为空字符串的情况)。

ui7jx7zq

ui7jx7zq3#

或者,您也可以使用CASE来执行以下操作:

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

tv6aics14#

您可以在IF中使用the IFNULL function,这样会更短一些,字段名的重复也会更少。

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

kx7yvsdv5#

您可以创建一个函数来简化此操作。

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
jtoj6r0c

jtoj6r0c6#

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

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
voase2hg

voase2hg7#

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
uqdfh47h

uqdfh47h8#

如果你想签入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!";
}

相关问题