Come verificare se il campo è nullo o vuoto in MySQL?


91

Sto cercando di capire come controllare se un campo è NULLo vuoto . Ho questo:

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

Devo aggiungere un ulteriore controllo field1 != ""qualcosa come:

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

Qualche idea su come ottenere questo risultato?

Risposte:


201

In entrambi i casi

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

o

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

Se vuoi solo controllare nulle non per stringhe vuote, puoi anche usare ifnull()o coalesce(field1, 'empty'). Ma questo non è adatto per stringhe vuote.


14

In alternativa puoi anche usare CASEper lo stesso:

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


9

Puoi usare la IFNULLfunzione all'interno di IF. Questo sarà un po 'più breve e ci saranno meno ripetizioni del nome del campo.

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

6

Puoi creare una funzione per renderlo facile.

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

Utilizzando:

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

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

qui chiunque può trovare lì la soluzione di qry. è un qry in esecuzione e spero che sia utile per tutti
user7256715

-1

Se desideri controllare in PHP, dovresti fare qualcosa come:

$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!";
}

3
$isnull = (empty($ertom['YOUROWNAME']) ? empty : not empty); È un po 'più breve ..
Robert de Jonge
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.