给出下面名为demo的表:
+----+-------+--------+
| id | bag_1 | bag_2 |
+----+-------+--------+
| 1 | Alpha | Alpha |
| 2 | Alpha | Beta |
| 3 | Beta | Beta |
| 4 | Beta | Omega |
| 5 | Beta | Delta |
| 6 | Beta | Sigma |
| 7 | Gamma | Alpha |
| 8 | Gamma | Lambda |
| 9 | Gamma | Omega |
+----+-------+--------+
如何在bag_1和bag_2列中找到不同值的计数?
(预期计数= 7)
注意:原始表有大约180万行,因此连接从未成功完成。
答案 0 :(得分:0)
可以使用UNION ALL
收集所有可能的值,然后COUNT(DISTINCT bag)
将完成其余的操作,如下所示:
SELECT COUNT(DISTINCT bag) from (SELECT bag_1 AS bag FROM demo UNION ALL SELECT bag_2 AS bag FROM demo) a;
+---------------------+
| count(distinct bag) |
+---------------------+
| 7 |
+---------------------+
编辑: @Tim Biegeleisen和@eggyal的屈膝礼,一个较短的形式是:
SELECT COUNT(*) from (SELECT bag_1 AS bag FROM demo UNION SELECT bag_2 AS bag FROM demo) a;