如果存在数据,则...使用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