MySQL,计算表中“填充”字段的数量

时间:2011-01-18 23:51:05

标签: php mysql count

MySQL(表格):

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

输出:

5

但是,如果可能的话,我还想在同一个查询中计算填充文本字段

结果:

5 in total
3 with filled text fields

2 个答案:

答案 0 :(得分:9)

SELECT COUNT(*) AS `total`, SUM(IF(`text` <> "",1,0)) AS `non_empty` FROM `table`

答案 1 :(得分:4)

这可以通过子查询很好地完成。

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

自我注意:在提交之前开始校对您的工作。