我将用一个简单的例子来介绍我的问题。
我在同一个表上有两个通用查询,例如表'customers'
定义'plushes'一个包含店内加号信息的表,下面的第一个查询检索客户的某个子集,比如第一个子集,他们的首选长毛。
WITH preferences
AS
(
SELECT CustomerID,
CustomerName,
City,
Country,
PlushType,
PlushPrice
FROM customers cs
LEFT JOIN plushes ps
ON cs.CustomerID = ps.CustomerID
WHERE cs.CustomerID < 4
)
SELECT CustomerID, PlushType, PlushPrice
FROM preferences
以同样的方式,定义'菜肴'包含世界着名菜肴的表格,第二个查询检索另一个客户子集,说第二个子集,他们喜欢的菜。
WITH foodPreferences
AS
(
SELECT CustomerID,
CustomerName,
City,
Country,
FoodName,
FoodPrice
FROM customers cs
LEFT JOIN foods fs
ON cs.CustomerID = fs.CustomerID
WHERE fs.FoodName = 'pizza'
)
SELECT CustomerID, FoodName
FROM foodPreferences -- it returns customer 6
我正在搜索的是一个查询,显示第一个或第二个子集的客户的customerID,plushType,plushPrice,即:
这意味着,我想将第一个查询应用于第一个或第二个(从另一个查询派生)子集。 换句话说,我想为喜欢披萨的客户运行第一个查询。
我正在使用带有PL / Sql语言的OracleDB。
有什么想法吗?
P.S。我知道,对于书面示例,使用的查询的结构看起来很奇怪。实际上,我正在处理更复杂的事情,我更愿意反映我所拥有的查询的结构
答案 0 :(得分:1)
此查询将执行:
select customerid, plushtype, plushprice
from customers cs
left join plushes ps on cs.customerid = ps.customerid
where customerid in (
select customerid
from customers
where customerid < 4
)
or customerid in (
select customerid
from customers cs
left join foods fs on cs.customerid = fs.customerid
where fs.foodname = 'pizza'
);
答案 1 :(得分:1)
添加了更有效的新答案:
with selected_customers (customerid) as (
select customerid
from customers
where customerid < 4
union
select customerid
from customers
left join foods fs on cs.customerid = fs.customerid
where fs.foodname = 'pizza'
)
select customerid, ps.plushtype, ps.plushprice
from selected_customers cs
left join plushes ps on cs.customerid = ps.customerid;