MySQL - two accounts with different WHERE in one request

table

field1 field2 a 1 b c 3 e 4 f 

I need to count field1 and not empty field2 on request:

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

the result should be 5 and 3 in one query .

Is it possible?

+6
mysql
source share
4 answers

Just like a cake :)

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

Result:

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

If the null values ​​in the field2 column are equal to '' (empty rows) instead of the actual NULL , you can try the following:

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

Another way:

 SELECT COUNT(field1), COUNT(IF(field2='', NULL, field2)) FROM ... 
+4
source share

to combine query results with the same column formats, use UNION between them

 SELECT w FROM x UNION SELECT y FROM z 
0
source share

All Articles