如何检查字段为空或空mysql?

我想弄清楚如何检查一个字段为空或空。 我有这个

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

我需要添加额外的检查field1!=“”类似

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

任何想法如何做到这一点?

要么用

 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而不是空string,那么你也可以使用ifnull 。 但这也不适合空串。

或者,你也可以使用CASE相同的:

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

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

你可以创build一个函数来简化这个过程。

 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