我想合并两个查询。
我有 Query1 返回一些 ID。
然后我有 Query2,它首先检查表中是否存在一些 Id。如果否,则结果将是 Query1 返回的 Id。
如果是,那么我想要 Query1 和 Query2 返回的常见 Id,例如 Query1 和 Query2 返回的 Id 的交集。
那么我怎样才能在一个查询中做到这一点。
我想合并两个查询。
我有 Query1 返回一些 ID。
然后我有 Query2,它首先检查表中是否存在一些 Id。如果否,则结果将是 Query1 返回的 Id。
如果是,那么我想要 Query1 和 Query2 返回的常见 Id,例如 Query1 和 Query2 返回的 Id 的交集。
那么我怎样才能在一个查询中做到这一点。
这可以使用 DECODE 和 CASE 语句的组合来实现
SELECT DISTINCT BT1.ID
FROM BUFFER_TABLE_1 BT1, BUFFER_TABLE_2 BT2
WHERE DECODE((SELECT COUNT(BT1.ID)
FROM BUFFER_TABLE_1 BT1, BUFFER_TABLE_2 BT2
WHERE BT1.ID = BT2.ID),
0,
'TRUE',
(SELECT CASE
WHEN BT1.ID = BT2.ID THEN
'TRUE'
ELSE
'FALSE'
END
FROM DUAL)) = 'TRUE'
ORDER BY BT1.ID
主要部分在解码中使用,如果两个表中的匹配 ID 计数为零,则从第一个表(BUFFER_TABLE_1)返回所有 ID。但是,如果此计数大于 0,则两个表中的 ID 都匹配,并且仅返回公共 ID
希望能帮助到你
(For people who have already read my answer: It has been hugely re-edited because of the comments of @nawfal that I want to preserve)
First I want to clarify that I understood your problem correct.
You have the Parts:
select id from table1
That produces Result1select id from table2 where <some condition>
That produces Result2select count(id) > 0 from table2 where <some condition>
That decides what result to useIf 3. returns more than 1 then you want the rows that are returned by 1. AND 2. (but not the ones that are only returned by 1. OR only by 2.)
If 3. returns 0 then you want the results of 1.
-> The solution is to have 3. in a view and select it in a where clause of a union statement TWICE.
Like this:
SELECT t1.id FROM table1 t1 WHERE
(SELECT COUNT(t2.id) from table2 t2 where <some condition>) = 0
UNION
select t2.id from table2 t2 WHERE <some condition>
AND t2.id IN (SELECT t1.id FROM table1 t1)
AND (SELECT COUNT(t2.id) from table2 t2 where <some condition>) > 0
one of the two parts will always be empty (because query 3. can't be = 0 and > 0 at the same time)