sql >> Databáze >  >> RDS >> Mysql

Počítejte neprázdná pole mysql

Kód se pokusí spočítat počet řádků, kde všechna pole nejsou nulová. Měli byste používat is not null spíše než jen not null .

Chcete-li spočítat počet polí, použijte toto:

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

Počítání počtu řádků:

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:

Pokud jsou prázdné, použijte tuto logiku:

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. Jak profilovat PostgreSQL databázi?

  2. Jíst naše vlastní krmivo pro psy – Spuštění JIRA na MariaDB

  3. Zkontrolujte, zda jsou dva výběry ekvivalentní

  4. PostgreSQL - deaktivace omezení