Mysql
 sql >> Database >  >> RDS >> Mysql

Conta i campi non vuoti mysql

Il codice tenta di contare il numero di righe in cui tutti i campi non sono nulli. Dovresti usare is not null piuttosto che solo not null .

Per contare il numero di campi, usa questo:

SELECT sum((listing_photo_1 IS NOT NULL) +
           (listing_photo_2 IS NOT NULL) +
           (listing_photo_3 IS NOT NULL) +
           (listing_photo_4 IS NOT NULL) +
           (listing_photo_5 IS NOT NULL) +
           (listing_photo_6 IS NOT NULL) +
           (listing_photo_7 IS NOT NULL) +
           (listing_photo_8 IS NOT NULL)
          ) as total
from listings
WHERE pmpid = '$pmpid';

Per contare il numero di righe:

SELECT count(*) as total
from listings
WHERE listing_photo_1 IS NOT NULL AND
      listing_photo_2 IS NOT NULL AND 
      listing_photo_3 IS NOT NULL AND 
      listing_photo_4 IS NOT NULL AND 
      listing_photo_5 IS NOT NULL AND 
      listing_photo_6 IS NOT NULL AND 
      listing_photo_7 IS NOT NULL AND 
      listing_photo_8 IS NOT NULL AND 
      pmpid = '$pmpid'";

MODIFICA:

Se sono vuoti, usa una logica come questa:

SELECT sum((listing_photo_1 IS NOT NULL and listing_photo_1 <> '') +
           (listing_photo_2 IS NOT NULL and listing_photo_2 <> '') +
           (listing_photo_3 IS NOT NULL and listing_photo_3 <> '') +
           (listing_photo_4 IS NOT NULL and listing_photo_4 <> '') +
           (listing_photo_5 IS NOT NULL and listing_photo_5 <> '') +
           (listing_photo_6 IS NOT NULL and listing_photo_6 <> '') +
           (listing_photo_7 IS NOT NULL and listing_photo_7 <> '') +
           (listing_photo_8 IS NOT NULL and listing_photo_8 <> '')
          ) as total
from listings
WHERE pmpid = '$pmpid';