单个 sql 查询中相同字段的相等、不相等条件

Equal, Not equal conditions on same field in single sql query

以下是 table 调用页面的架构,它是 mysql 5.6 服务器

上的 运行
+---------------+------------------+------+-----+---------+----------------+
| 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;

您甚至可以使用 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`;
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

请尝试上面的代码,希望这会有所帮助。