表
field1 field2
a 1
b
c 3
e 4
f
我需要在查询中计算field1和not empty field2
:
SELECT COUNT(field1) FROM table
+
SELECT COUNT(field2) FROM table WHERE field2 != ''
结果应为5和3 in one query
。
有可能吗?
答案 0 :(得分:11)
像饼一样容易:)
select count(field1), count(field2)
from my_table
结果:
+--------+--------+
| field1 | field2 |
+--------+--------+
| 5 | 3 |
+--------+--------+
如果field2
列中的空值为''
(空字符串)而非实际NULL
,则可以尝试以下操作:
select count(field1), sum(case when field2 != '' then 1 else 0 end)
from my_table;
答案 1 :(得分:7)
SELECT
(SELECT COUNT(field1) FROM table) AS count1,
(SELECT COUNT(field2) FROM table WHERE field2 != '') AS count2
答案 2 :(得分:4)
另一种方式:
SELECT COUNT(field1), COUNT(IF(field2='', NULL, field2))
FROM ...
答案 3 :(得分:0)
将查询结果与相同的列格式相结合,在它们之间使用UNION
SELECT w FROM x
UNION
SELECT y FROM z