问题描述
我有这种简单的查询,它为给定的 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');
这篇关于即使没有结果也返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!