Returning a value even if no result(即使没有结果也返回一个值)
问题描述
我有这种简单的查询,它为给定的 id 返回一个非空的整数字段:
I have this kind of simple query that returns a not null integer field for a given id:
SELECT field1 FROM table WHERE id = 123 LIMIT 1;
问题是如果找不到 id,则结果集为空.我需要查询总是返回一个值,即使没有结果.
The thing is if the id is not found, the resultset is empty. I need the query to always return a value, even if there is no result.
我有这个东西,但我不喜欢它,因为它运行了 2 次相同的子查询:
I have this thing working but I don't like it because it runs 2 times the same subquery:
SELECT IF(EXISTS(SELECT 1 FROM table WHERE id = 123) = 1, (SELECT field1 FROM table WHERE id = 123 LIMIT 1), 0);
如果该行存在,则返回 field1,否则返回 0.有什么方法可以改进吗?
It returns either field1 if the row exists, otherwise 0. Any way to improve that?
谢谢!
根据一些评论和答案进行编辑:是的,它必须在单个查询语句中,我不能使用计数技巧,因为我需要返回只有 1 个值(仅供参考,我使用 Java/Spring 方法 SimpleJdbcTemplate.queryForLong() 运行查询).
Edit following some comments and answers: yes it has to be in a single query statement and I can not use the count trick because I need to return only 1 value (FYI I run the query with the Java/Spring method SimpleJdbcTemplate.queryForLong()).
推荐答案
MySQL 有一个函数可以在结果为空时返回一个值.您可以在整个查询中使用它:
MySQL has a function to return a value if the result is null. You can use it on a whole query:
SELECT IFNULL( (SELECT field1 FROM table WHERE id = 123 LIMIT 1) ,'not found');
这篇关于即使没有结果也返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:即使没有结果也返回一个值


- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- SQL 临时表问题 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01