简体   繁体   English

MySQL - 在一个查询中使用不同的WHERE计数两次

[英]MySQL - two counts with different WHERE in one query

table

field1 field2
a       1
b
c       3
e       4
f

I need to count field1 and not empty field2 with on query: 我需要在查询时计算field1而not empty field2

SELECT COUNT(field1) FROM table
+
SELECT COUNT(field2) FROM table WHERE field2 != ''

result should be 5 and 3 in one query . in one query结果应为5和3。

Is it possible? 可能吗?

Easy as pie :) 易如反掌 :)

select count(field1), count(field2)
from my_table

Result: 结果:

+--------+--------+
| field1 | field2 |
+--------+--------+
| 5      | 3      |
+--------+--------+

If the empty values in the field2 column are '' (empty strings) instead of actual NULL , you can try this: 如果field2列中的空值为'' (空字符串)而不是实际的NULL ,则可以尝试:

select count(field1), sum(case when field2 != '' then 1 else 0 end)
from my_table;
SELECT
    (SELECT COUNT(field1) FROM table) AS count1,
    (SELECT COUNT(field2) FROM table WHERE field2 != '') AS count2

Yet another way: 另一种方式:

SELECT COUNT(field1), COUNT(IF(field2='', NULL, field2))
    FROM ...

to combine the results of queries with identical column formats, use UNION between them 要将查询结果与相同的列格式组合,请在它们之间使用UNION

SELECT w FROM x
UNION
SELECT y FROM z

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM