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');
这篇关于即使没有结果也返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:即使没有结果也返回一个值
基础教程推荐
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 无法解决整理冲突 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
