以下是在 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 = "";
谢谢
最佳答案
在 MySQL 中,你可以非常干净地写出这样的代码:
select sum(email <> "") not_blank, sum(email = "") blank from pages;
它利用了 MySQL 中 true 的计算结果为 1,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;
关于mysql - 单个sql查询中同一字段的等于、不等于条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42641302/