如果没有找到记录,则返回一个值 [英] Return a value if no record is found

查看:28
本文介绍了如果没有找到记录,则返回一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有效的简单语句:

I have this simple statement that works:

SELECT idnumber FROM dbo.database WHERE number = '9823474'

如果该数字不存在于表中的任何位置,则失败.我想在此声明中添加一些内容:
如果没有找到记录,则返回 NULL 而不是 NO ROW.

If the number does not exist anywhere in the table, it fails. I would like to add something to this statement that says:
IF NO RECORD IS FOUND RETURN NULL INSTEAD OF NO ROW.

有什么建议吗?

推荐答案

将查询封装在子查询中 转换无行"为 NULL 值.

Encapsulate the query in a sub-query to transform "no row" to a NULL value.

我使用 PostgreSQLSQL ServerMySQL.也适用于 SQLite.

SELECT (SELECT id FROM tbl WHERE id = 9823474) AS id;

Oracle 你必须像这样从虚拟的 1 行表 DUAL 中选择:

SELECT (SELECT id FROM tbl WHERE id = 9823474) AS id FROM DUAL;

出于兼容性原因,您可以在 MySQL 中执行相同的操作,但您不必这样做.
类似于 Firebird:

You can do the same in MySQL for compatibility reasons, but you don't have to.
Similar in Firebird:

SELECT (SELECT id FROM tbl WHERE id = 9823474) AS id FROM RDB$DATABASE;

这是为了 <强>DB2(如肖恩评论):

SELECT (SELECT id FROM tbl WHERE id = 9823474) AS id FROM SYSIBM.SYSDUMMY1;

替代UNION ALL

SELECT id FROM tbl WHERE id = 9823474
UNION  ALL
SELECT NULL -- FROM DUAL  -- for Oracle
FETCH FIRST 1 ROW ONLY;

标准 SQL,但我只用 Postgres 测试过,它的评估如下:
如果在第一个 SELECT 中找到一行,则返回该行.由于 LIMIT 1 (FETCH FIRST 1 ROW ONLY),一旦找到第一行,Postgres 就会停止寻找更多行.
第二个 SELECT 仅在第一个不返回任何内容时才会执行.NULL 值的数据类型由tbl.id 的数据类型自动确定.

Standard SQL, but I only tested this with Postgres, which evaluates like this:
If a row is found in the first SELECT, it is returned. Postgres stops looking for more rows, as soon as the first is found due to LIMIT 1 (FETCH FIRST 1 ROW ONLY).
The second SELECT is only even executed if the first returns nothing. The data type of the NULL value is determined by the data type of tbl.id automatically.

关于LIMIT 子句:

这篇关于如果没有找到记录,则返回一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆