MySQL, count the number of filled fields in a table

MySQL (table):

+----+------+
| id | text |
+----+------+
| 1  |      |
+----+------+
| 2  | blah |
+----+------+
| 3  |      |
+----+------+
| 4  | blah |
+----+------+
| 5  | blah |
+----+------+

PHP:

$a = mysql_query("SELECT COUNT(*) AS count1 FROM `table`");
$b = mysql_fetch_assoc($a);

echo $b['count1'];

Conclusion:

5

However, I also want to consider the text fields filled - in the same query, if possible.

Result:

5 in total
3 with filled text fields
+3
source share
2 answers
SELECT COUNT(*) AS `total`, SUM(IF(`text` <> "",1,0)) AS `non_empty` FROM `table`
+9
source

This can be done pretty well with subqueries.

SELECT COUNT(id) AS id, COUNT(SELECT text FROM 'table' WHERE text IS NOT NULL) AS t FROM 'table'

Note to yourself: start proofreading your work before submitting it.

+4
source

Source: https://habr.com/ru/post/1786268/


All Articles