MySQL多列单查询
我有一个数据库,保存客户的数据。我需要知道我们在各个城市和国家有多少客户。我必须用一个查询来完成它 我的表是customers,我有city列和country列(都是varchar),其中包含关于它的信息 所需的查询输出应如下所示:MySQL多列单查询,mysql,sql,multiple-columns,Mysql,Sql,Multiple Columns,我有一个数据库,保存客户的数据。我需要知道我们在各个城市和国家有多少客户。我必须用一个查询来完成它 我的表是customers,我有city列和country列(都是varchar),其中包含关于它的信息 所需的查询输出应如下所示: City | NumberOfCustomers | Country | NumberOfCustomers | -------------------------------------------------------- 谢谢 编辑以显示该查询的示例表和输出
City | NumberOfCustomers | Country | NumberOfCustomers |
--------------------------------------------------------
谢谢
编辑以显示该查询的示例表和输出:
mysql> select * from location;
+-------+---------+
| city | country |
+-------+---------+
| City1 | US |
| City2 | US |
| City2 | US |
| City3 | CA |
| City3 | CA |
| City3 | JP |
+-------+---------+
6 rows in set (0.00 sec)
mysql> select city, country, count(*) from location group by 1,2 with rollup;
+-------+---------+----------+
| city | country | count(*) |
+-------+---------+----------+
| City1 | US | 1 |
| City1 | NULL | 1 |
| City2 | US | 2 |
| City2 | NULL | 2 |
| City3 | CA | 2 |
| City3 | JP | 1 |
| City3 | NULL | 3 |
| NULL | NULL | 6 |
+-------+---------+----------+
8 rows in set (0.01 sec)
期望的输出很奇怪。不客气,“我必须用单次查询来完成”——这项要求背后有什么技术原因?@zerkms“因为我的老师告诉过我。”@Crontab:我打赌不是这样,而是类似于“因为一次查询比两次查询快”:-@zerkms你可能是对的MySQL是否支持带有的
@showdev-我更新了一个示例来说明mysql的“with”是如何实现的used@atxdba谢谢有没有办法把他们分组?像USA-36而不是USA-1在36行?@atxdba感谢编辑,看起来我很困惑。
mysql> select * from location;
+-------+---------+
| city | country |
+-------+---------+
| City1 | US |
| City2 | US |
| City2 | US |
| City3 | CA |
| City3 | CA |
| City3 | JP |
+-------+---------+
6 rows in set (0.00 sec)
mysql> select city, country, count(*) from location group by 1,2 with rollup;
+-------+---------+----------+
| city | country | count(*) |
+-------+---------+----------+
| City1 | US | 1 |
| City1 | NULL | 1 |
| City2 | US | 2 |
| City2 | NULL | 2 |
| City3 | CA | 2 |
| City3 | JP | 1 |
| City3 | NULL | 3 |
| NULL | NULL | 6 |
+-------+---------+----------+
8 rows in set (0.01 sec)