Mysql查询联合所有

时间:2014-04-02 07:39:26

标签: mysql sql

我在MySQL DB中执行了两个查询。

两个查询之间的唯一区别是这个附加条件:

WHERE
    Action > ''

两个问题:

mysql> SELECT
 COUNT(DISTINCT tel_number) AS `cases present`
FROM
    `tbl_tel_number`
WHERE
    Consuming IS NOT NULL
GROUP BY
    Zone,
    Consuming
LIMIT 3;

SELECT
 COUNT(DISTINCT tel_number) AS `cases analyzed`
FROM
    `tbl_tel_number`
WHERE
    Action > ''
GROUP BY
    Zone,
    Consuming
LIMIT 3;
+---------------+
| cases present |
+---------------+
|             7 |
|            27 |
|            27 |
+---------------+
3 rows in set

+-----------------+
| cases analyzed  |
+-----------------+
|               1 |
|               3 |
|               3 |
+-----------------+
3 rows in set

现在我尝试联合两个查询的结果集并测试了这个解决方案:

mysql> SELECT
 COUNT(DISTINCT tel_number) AS `cases present`,
 CASE
WHEN Action > '' THEN
    COUNT(DISTINCT tel_number)
ELSE
    0
END AS `cases analyzed`
FROM
    `tbl_tel_number`
WHERE
    Consuming IS NOT NULL
GROUP BY
    Zone,
    Consuming
LIMIT 3;


+---------------+-----------------+
| cases present | cases analyzed  |
+---------------+-----------------+
|             7 |               0 |
|            27 |               0 |
|            27 |              27 |
+---------------+-----------------+
3 rows in set

mysql> 

但是输出是错误的,因为在分析的案例的第二个查询中我是

+-----------------+
| cases analyzed  |
+-----------------+
|               1 |
|               3 |
|               3 |
+-----------------+
3 rows in set

相反,在我所分析的案例的联合查询中,为什么?

+-----------------+
| cases analyzed  |
+-----------------+
|               0 |
|               0 |
|              27 |
+-----------------+
3 rows in set

1 个答案:

答案 0 :(得分:3)

您希望将条件置于计数内:

SELECT COUNT(DISTINCT tel_number) AS `cases present`,
       COUNT(DISTINCT CASE WHEN Action > '' THEN tel_number END) as `cases analyzed`
FROM `tbl_tel_number`
WHERE Consuming IS NOT NULL
GROUP BY Zone, Consuming
LIMIT 3;