以下是在mysql 5.6服务器上运行的名为pages的表的模式
+---------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| city | varchar(255) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
+---------------+------------------+------+-----+---------+----------------+
我想将以下2个sql查询组合成单个sql查询,这可能吗?我尝试使用嵌套查询,但没有得到理想的结果。
select count(*) from pages where email != "";
select count(*) from pages where email = "";
由于
答案 0 :(得分:2)
在MySQL中,你可以非常干净地写出来:
select sum(email <> "") not_blank, sum(email = "") blank from pages;
它使用了以下事实:true计算结果为1,而在MySQL中,false计算结果为0。
在其他DBMS中,等效查询将是:
select sum(case when email <> "" then 1 else 0 end) not_blank,
sum(case when email = "" then 1 else 0 end) blank
from pages;
如果您想使用COUNT
:
select count(case when email <> "" then 1 end) not_blank,
count(case when email = "" then 1 end) blank
from pages;
答案 1 :(得分:0)
您甚至可以使用CASE
表达式。
<强>查询强>
select
sum(case when trim(`email`) = "" or `email` is null then 1 else 0 end) `is_null`,
sum(case when trim(`email`) <> "" or `email` is not null then 1 else 0 end) `is_not_null`
from `pages`;
答案 2 :(得分:0)
SELECT SUM(NOT_BLANK) NOT_BLANK,SUM(BLANK) BLANK FROM
(
select count(*) as NOT_BLANK,0 as BLANK from pages where email != "";
UNION ALL
select 0 as NOT_BLANK,count(*) as BLANK from pages where email = "";
)ZZ
请尝试上面的代码,希望这会有所帮助。