如果没有找到记录,Mysql 计数返回零

发布于 2024-08-07 02:46:43 字数 387 浏览 5 评论 0原文

我有两张桌子。

cities - id_city, city_name
properties - id_property, id_city, property_name

我想显示 cities.city_name 及其旁边的 [properties.count(id_city)]

如何进行查询,如果没有找到记录,仍然返回零而不是NULL,以便我得到如下结果:

London [123]
New York [0]
Berlin [11]

其中“New York”是 [0],而不是 NULL 也不是 1?

I have a two tables.

cities - id_city, city_name
properties - id_property, id_city, property_name

I want to display cities.city_name and next to it [properties.count(id_city)]

How do I make a query that still returns zero if no records are found instead of NULL, so that I get results like this:

London [123]
New York [0]
Berlin [11]

where "New York" is [0], not NULL and not 1?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

第七度阳光i 2024-08-14 02:46:43

使用外连接:

select cities.city_name, count(properties.id_city)
  from cities left join properties on cities.id_city = properties.id_city
  group by 1

Use an outer join:

select cities.city_name, count(properties.id_city)
  from cities left join properties on cities.id_city = properties.id_city
  group by 1
ヅ她的身影、若隐若现 2024-08-14 02:46:43

我认为以下内容可以为您做到这一点,尽管我还没有测试过。诀窍是获取一个表中的属性计数,然后将该表左连接到城市表,使用 IFNULL 函数。

SELECT city_name, IFNULL(property_count, 0)
FROM cities
LEFT JOIN
   (SELECT id_city, count(*) as property_count
    FROM properties
    GROUP BY id_city) city_properties
   USING (id_city);

I think the following will do it for you, though I haven't tested it. The trick is to get the property counts in one table, and then to left join that table to the cities table, converting NULLs to 0s using the IFNULL function.

SELECT city_name, IFNULL(property_count, 0)
FROM cities
LEFT JOIN
   (SELECT id_city, count(*) as property_count
    FROM properties
    GROUP BY id_city) city_properties
   USING (id_city);
一个人的旅程 2024-08-14 02:46:43

查询:

SELECT cities.*, COUNT(properties.id_city) as num
FROM cities
LEFT JOIN properties on cities.id_city=properties.id_city
GROUP BY cities.id_city

应该在你想要的地方返回一个 0 计数,尽管我不能 100% 确定它在 MySQL 中是这样工作的。

The query:

SELECT cities.*, COUNT(properties.id_city) as num
FROM cities
LEFT JOIN properties on cities.id_city=properties.id_city
GROUP BY cities.id_city

should return a 0 count where you want it, although I'm not 100% certain it works that way in MySQL.

暮年 2024-08-14 02:46:43

简单的。使用“(计数(*)+ 0)”。任何 null 加 0 都会返回一个数字。

Simple. Use "(Count(*) + 0)". Any null plus 0 will return a number.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文