如果未找到记录,则返回一个值

时间:2011-11-11 19:15:02

标签: sql select null record

我有这个简单的陈述:

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

如果表中的任何位置都不存在该号码,则会失败。我想在这句话中加上一些说法:
如果没有记录被发现,则返回NULL,不得行。

有什么建议吗?

4 个答案:

答案 0 :(得分:57)

在子查询中封装查询,将“no row”转换为NULL值。

我使用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

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

这适用于DB2(例如Sean commented):

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 1FETCH FIRST 1 ROW ONLY),Postgres会在找到第一行时停止查找更多行。
第二个SELECT只有在第一个没有返回时才执行。 NULL值的数据类型由tbl.id的数据类型自动确定。

关于LIMIT条款:

答案 1 :(得分:6)

为了使它更简单,这应该工作正常。如果根据idnumber的数据类型将此值赋给变量,则可以评估该值是null还是实际的idnumber返回。

SELECT ISNULL(
      (
         SELECT idnumber 
         FROM dbo.database 
         WHERE number = '9823474'
      ), NULL)

答案 2 :(得分:3)

Select isnull(sum(Amount),0) as Amt from BeginningBalance where CustomerID = @CustomerID
Union all
Select isnull(sum(Amount),0) as Amt from SalesOrders where CustomerID = @CustomerID
Union all
Select isnull(sum(Amount),0) as Amt from SalesInvoices where CustomerID = @CustomerID
//Data Row Result if no data is present at Beginning Balance Table
// example 

Amt
2000  // amount from sales orders
1000  // amount from sales invoices

// if the 1st select statement return no data use this
SELECT (select sum(Amount) from BeginningBalance 
        where CustomerID = @CustomerID) as Amt
Union all
Select sum(Amount) as Amt from SalesOrders where CustomerID = @CustomerID
Union all
Select sum(Amount) as Amt from SalesInvoices where CustomerID = @CustomerID

结果:

Amt
NULL  // amount from BeginningBalance
2000  // amount from sales orders
1000  // amount from sales invoices

答案 3 :(得分:0)

我将它用于MySql

SELECT IFNULL(ColumnA,"1") AS ColumnA , COUNT(1) AS Total FROM table 
WHERE ID = 1 LIMIT 0, 1;