I have a view
x
create or replace view v_collected as
select car.id_car
,car.state_car
,[..]
from cars car
,garages garage
,[..]
where [..]
Which is at least unique for car.id
Now I want to union 3 different queries into a second view, which takes user set parameters:
select 0 as score
,p0.*
from v_collected p0
where 1 = 1
-- User IO Binding
and p0.car = 'Audi'
and p0.garage = 'P01'
and p0.state_car = 'Ok'
union
select 1 as score
,p1.*
from v_collected p1
where 1 = 1
-- Should access the identical binding
and p1.car <> p0.car
and p1.state_car = p0.state_car
union
select 2 as score
,p2.*
from v_collected p2
where 1 = 1
-- Should access the identical binding
and p2.state_car = p0.state_car
The above does not work as the 2nd query has no access to the the 1st one. As the constraints change, I believe I cannot use a CTE. What are my options?
Advertisement
Answer
Since the requirements are vague, I can’t say for sure that the following solution is complete, however, I would look into breaking the p0, p1, p2 into with clause sub queries that way you can use p0 in p1 and p2. For example:
with cars as
(
select 2 id_car, 'Ford' car, 'Ok' state_car from dual union
select 1 id_car, 'Audi' car, 'Ok' state_car from dual
)
, garages as
(
select 2 id_car, 'P02' garage from dual union
select 1 id_car, 'P01' garage from dual
)
, v_collected as
(
select car.id_car
,car.car
,car.state_car
,garage.garage
from cars car
,garages garage
where 1=1
and car.id_car = garage.id_car
)
-- select * from v_collected;
, p0_subquery as
(
select 0 as score
,p0.*
from v_collected p0
where 1 = 1
-- User IO Binding
and p0.car = 'Audi'
and p0.garage = 'P01'
and p0.state_car = 'Ok'
)
--select * from p0_subquery;
, p1_subquery as
(
select 1 as score
,p1.*
from v_collected p1
, p0_subquery p0
where 1 = 1
-- Should access the identical binding
and p1.car <> p0.car
and p1.state_car = p0.state_car
)
, p2_subquery as
(
select 2 as score
,p2.*
from v_collected p2
, p0_subquery p0
where 1 = 1
-- Should access the identical binding
and p2.state_car = p0.state_car
)
select * from p0_subquery
union
select * from p1_subquery
union
select * from p2_subquery
;