MySQL 中 COUNT 的默认值
我有一个看起来像这样的表:
+-------+-----+
|country|prop1|
+-------+-----+
|RO | 1 |
|RO | 2 |
|UK | 1 |
|IT | 2 |
+-------+-----+
我想计算 prop1 不为空的行,我使用以下选择:
SELECT `country`, COUNT(*) as number FROM table GROUP BY `country`;
这将返回:
+-------+------+
|country|number|
+-------+------+
|RO | 2 |
|UK | 1 |
|IT | 1 |
+-------+------+
但是我需要以下内容:
+-------+------+
|country|number|
+-------+------+
|RO | 2 |
|UK | 1 |
|IT | 1 |
|FR | 0 |
+-------+------+
你认为这样的东西可以写吗直接在SQL中?我在想类似指定“国家”的可能值列表和默认值(0)(如果在表中找不到)。
I have a table looking something like this:
+-------+-----+
|country|prop1|
+-------+-----+
|RO | 1 |
|RO | 2 |
|UK | 1 |
|IT | 2 |
+-------+-----+
I want to count the rows for which the prop1 is not null and I use the following select:
SELECT `country`, COUNT(*) as number FROM table GROUP BY `country`;
this will return:
+-------+------+
|country|number|
+-------+------+
|RO | 2 |
|UK | 1 |
|IT | 1 |
+-------+------+
however I need the following:
+-------+------+
|country|number|
+-------+------+
|RO | 2 |
|UK | 1 |
|IT | 1 |
|FR | 0 |
+-------+------+
Do you think something like this can be possible to write directly in SQL? I was thinking something like specifying list of possible values for "country" and a default value (0) if it is not found in the table.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的示例中,
FR
来自何处并不明显。MySQL
内部没有国家/地区列表,因此应从某处获取国家/地区代码。如果您在
mytable
中包含所有国家/地区(prop
可能设置为NULL
):如果您在单独的表中包含国家/地区(并且一个国家/地区可能会
mytable
中缺失):It's not obvious in your example where the
FR
comes from.MySQL
does not have a list of countries inside it, so country codes should be taken from somewhere.If you have all countries inside
mytable
(withprop
possibly set toNULL
):If you have countries in a separate table (and a country may be missing in
mytable
):我认为你必须与所有国家建立一张桌子。最好更改当前的表以使用国家/地区的键。这样您就可以进行 LEFT JOIN。这将为您提供所有国家/地区,如果该国家/地区没有道具,则值为 NULL。
I think you will have to set up a table with all the countries. It will be best to alter your current table to use the keys of the countries. So that you can do a LEFT JOIN. That will give you all the countries, with NULL values if there are no props for that country.