Sql 合并两个查询
我将用一个简单的例子来介绍我的问题 我在同一个表上有两个通用查询,比如表'customers' 定义“plushs”一个包含店内plushs信息的表,下面的第一个查询检索特定客户子集,例如第一个子集,他们的首选plushsSql 合并两个查询,sql,oracle,Sql,Oracle,我将用一个简单的例子来介绍我的问题 我在同一个表上有两个通用查询,比如表'customers' 定义“plushs”一个包含店内plushs信息的表,下面的第一个查询检索特定客户子集,例如第一个子集,他们的首选plushs WITH preferences AS ( SELECT CustomerID, CustomerName, City, Country, PlushType, PlushPrice FROM customers c
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
我要搜索的是一个查询,显示第一个子集或第二个子集的客户的customerID、plushType、plushPrice,即:
这意味着,我想将第一个查询应用于从另一个查询子集派生的第一个或第二个查询。
换句话说,我想为那些喜欢比萨饼的顾客运行第一个查询
我正在使用OracleDB和PL/Sql语言
有什么想法吗
另外,我知道对于编写的示例,所用查询的结构看起来很奇怪。事实上,我正在处理更复杂的问题,我更喜欢镜像我的查询结构此查询可以:
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'
);
此查询将执行以下操作:
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'
);
添加了更高效的新答案:
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;
添加了更高效的新答案:
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;
Oracle,更详细的Pl/SQL第二个子集没有plushType或plushPrice,您希望如何为第二个子集的客户显示plushType和plushPrice?我认为您需要给出一个更具体的示例,最好是在SQL FIDDLE中,第二个查询定义了客户的子集。对于这些客户,我想运行第一个queryracle,更详细地说是Pl/sql。第二个子集没有plushType或plushPrice,您希望如何为第二个子集的客户显示plushType和plushPrice?我认为您需要给出一个更具体的示例,最好是在SQL FIDDLE中,第二个查询定义了客户的子集。对于这些客户,我想运行第一个查询您是对的,但您的回答是基于您可以独立于第二个查询选择客户6这一事实。假设您事先不知道第二个查询检索到的第二个客户子集。为了让事情更清楚,我在第二个查询中更改了where语句。请根据您的新变化修改外观。谢谢:我已经尝试过此解决方案。。但是执行查询花了20多分钟,然后我停止了。。。。你知道,嵌套查询会破坏效率嘿,你一直在移动帖子不公平:哈哈,你是对的,我的朋友。但这是我真正的需要,不幸的是,你是对的,但你的回答是基于这样一个事实:你可以独立于第二个查询选择customer 6。假设您事先不知道第二个查询检索到的第二个客户子集。为了让事情更清楚,我在第二个查询中更改了where语句。请根据您的新变化修改外观。谢谢:我已经尝试过此解决方案。。但是执行查询花了20多分钟,然后我停止了。。。。你知道,嵌套查询会破坏效率嘿,你一直在移动帖子不公平:哈哈,你是对的,我的朋友。但不幸的是,这是我真正的需要