当Where子句中的术语不在数据库中时,如何从MySQL数据库返回0?
如果 WHERE 子句中的邻域不存在,如何让 mysql 数据库返回 0?因此,在下面的示例中,旧城区不在数据库中。我希望数据库返回 0 个事件而不是空结果。
SELECT incidents,
neighborhoods
FROM `myTable`
WHERE neighborhoods ='Old Town'
我也尝试过
SELECT IFNULL(incidents,0),
IFNULL(neighborhoods,0)
FROM `myTable`
WHERE neighborhoods ='Old Town'
任何建议将非常感激。
How do I get my mysql database to return 0 if the neighborhood in the WHERE clause doesn't exist? So in the example below, Old Town is not in the database. I'd like the database to return 0 incidents instead of an empty result.
SELECT incidents,
neighborhoods
FROM `myTable`
WHERE neighborhoods ='Old Town'
I also tried
SELECT IFNULL(incidents,0),
IFNULL(neighborhoods,0)
FROM `myTable`
WHERE neighborhoods ='Old Town'
Any suggestions would be really appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我对您的问题的看法是构建您希望找到的“neighborhoods”值的派生表,并“LEFT JOIN”到实际表:
My take on your issue is to construct a derived table of the
neighborhoods
values you hope to find, andLEFT JOIN
to the actual table:您可以将
COUNT(*)
添加到选择部分,这将为您提供结果集中的行数。只要您只想读取一行,它就会为您提供 0 或 1。但是,如果您要获取多于一行,则可能会失败,因为您只能从结果集中获取一行。
(并且不要忘记为
COUNT(*)
列使用别名)You can add
COUNT(*)
into the select part, which gives you the amount of rows in the result set. As long you want to read only one row it gives you either 0 or 1.But if you would get more than one row it may fail as you get only one row from the result set.
(And don't forget to use an alias for the
COUNT(*)
column)如果您需要从数据库返回 0 我建议使用函数。
否则,您可以在执行实际查询之前使用 COUNT() 查询从代码中检查是否存在。
If you need to return 0 from the DB i suggest using a function.
Otherwise, you could check existence from code by using a COUNT() query before executing the actual query.