简体   繁体   English

即使没有返回行也显示一个值

[英]displaying a value even if no rows returned

We have a situation in oracle SQL.我们在oracle SQL 中有一个情况。

select x from A where x=10;

so if 10 exists in the column, value will be displayed 10 .所以如果列中存在10 ,值将显示10 but if it doesn't exists I want to display null .但如果它不存在,我想显示null I tried NVL but it is not returning anything as data is not displaying.我尝试过NVL但由于未显示数据,因此它没有返回任何内容。

Could you please help me to resolve this.你能帮我解决这个问题吗?

If you want to return multiple rows from the original SELECT then you can use UNION ALL to add a row when the value does not exist:如果要从原始SELECT返回多行,则可以在值不存在时使用UNION ALL添加一行:

SELECT x
FROM   A
WHERE  x = 10
UNION ALL
SELECT NULL
FROM   DUAL
WHERE  NOT EXISTS (
  SELECT x
  FROM   A
  WHERE  x = 10
)

If your table is:如果您的表是:

CREATE TABLE a ( x ) AS
SELECT 10 FROM DUAL UNION ALL
SELECT 10 FROM DUAL UNION ALL
SELECT 10 FROM DUAL;

Then the query will output:然后查询将输出:

\n| | X | X |\n| | -: | -: |\n| | 10 | 10 |\n| | 10 | 10 |\n| | 10 | 10 |\n

Then if you DELETE FROM a;那么如果你DELETE FROM a; and repeat the query, it will output:并重复查询,它将输出:

\n| | X | X |\n| | ---: | ---: |\n| | null ||\n

db<>fiddle here db<> 在这里摆弄

Try this:尝试这个:

select max(x) 
from A
where x = 10; --this will return null if no data

And then you can do a NVL:然后你可以做一个NVL:

select nvl(max(x), 0) 
from A
where x = 10; --this will return 0 if no data

Where clause filter out the data what you are looking for, if it doesn't exists then query will return no record. Where子句过滤掉您要查找的数据,如果它不存在,则查询将不返回任何记录。

So, you can remove where clause & do aggregation :因此,您可以删除where子句并进行聚合:

select max(case when a.x = 10 then 10 end)
from a;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM