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

Tæl ikke-tomme felter mysql

Du koder forsøg på at tælle antallet af rækker, hvor alle felterne ikke er null. Du skal bruge is not null i stedet for bare not null .

For at tælle antallet af felter, brug dette:

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';

Sådan tælles antallet af rækker:

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'";

EDIT:

Hvis de er tomme, brug logik som denne:

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';


  1. Vis kun wordpress underkategorier

  2. Vis poster fra nu() til næste 7 dage i mysql

  3. Fremmednøgle mellem MySQL InnoDB-tabeller virker ikke... hvorfor?

  4. datoforskel, inklusive klokkeslæt