即使没有结果也返回一个值

2023-06-26数据库问题
0

本文介绍了即使没有结果也返回一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有这种简单的查询,它为给定的 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');

这篇关于即使没有结果也返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

Mysql目录里的ibtmp1文件过大造成磁盘占满的解决办法
ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致...
2025-01-02 数据库问题
151

SQL 子句“GROUP BY 1"是什么意思?意思是?
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)...
2024-04-16 数据库问题
62

MySQL groupwise MAX() 返回意外结果
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)...
2024-04-16 数据库问题
13

MySQL SELECT 按组最频繁
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)...
2024-04-16 数据库问题
16

为什么 Mysql 的 Group By 和 Oracle 的 Group by 行为不同
Why Mysql#39;s Group By and Oracle#39;s Group by behaviours are different(为什么 Mysql 的 Group By 和 Oracle 的 Group by 行为不同)...
2024-04-16 数据库问题
13

MySQL GROUP BY DateTime +/- 3 秒
MySQL GROUP BY DateTime +/- 3 seconds(MySQL GROUP BY DateTime +/- 3 秒)...
2024-04-16 数据库问题
14