如果存在数据,则...使用Oracle SQL? [英] If data exists, else... using Oracle SQL?

查看:72
本文介绍了如果存在数据,则...使用Oracle SQL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此刻我有两个查询,返回相同的数据,如果第一个查询没有返回结果,我希望第二个查询运行,这是我现在的PHP的基本思想:

I have two queries at the moment, returning the same data, I want the second query to run if the first returns no results, here's the basic idea of my PHP right now:

Run Query1
If Query1 returns a result
    Enter data into array
Else 
    Run Query2
    Enter data into array

我想知道的是,我可以仅使用Oracle SQL来做到这一点吗?因此,它只对数据库运行一个查询,对第一条语句进行快速检查,如果没有找到结果,则运行第二条语句?

What I'm wondering, is can I do that exclusively using Oracle SQL? So it'd just run a single query to the database, do a quick check of the first statement, and if no results are found run the second one?

谢谢

推荐答案

QUERY1
UNION ALL
QUERY2
WHERE NOT EXISTS (QUERY1)

例如:

SELECT id
  FROM products
    UNION ALL 
SELECT  id
  FROM old_products
    WHERE NOT EXISTS (SELECT id  FROM products) 

查询:

SELECT * 
    FROM Table 
WHERE ID = 7 
    AND Flag = 1
UNION ALL
SELECT * 
    FROM Table 
WHERE ID = 7 
    AND NOT EXISTS (select * from Table where ID = 7 and Flag = 1)

要确定唯一行,您也可以尝试以下操作:

To identifiy unique rows you can try this as well:

WITH qry AS
(
    SELECT a.* ,
        ROW_NUMBER() OVER(PARTITION BY id ORDER BY  Flag DESC ) rn
        FROM Table a
    WHERE ID = 7  -- THIS CAN BE PARAMETERIZED
)
SELECT * 
    FROM qry
WHERE rn = 1

这篇关于如果存在数据,则...使用Oracle SQL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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