【问题标题】:How to select and extract by using exists in oracle SQLoracle SQL中如何使用exist进行选择和提取
【发布时间】:2020-08-03 01:14:14
【问题描述】:

我想选择拥有type=a和product=1的客户

customer type product
A       a       1
A       b       1  
A       c       2 
B       b       2
B       b       1 
C       c       1
C       c       1

因此我想要的结果如下

customer type product
A       a       1
A       b       1  
A       c       2 

我想在下面的示例中添加选择器product = 1。

SELECT t1.customer, t1.type ,t1.product
FROM yourTable t1
WHERE EXISTS (SELECT 1 FROM yourTable t2 WHERE t2.customer = t1.customer AND t2.type = 'a');

因为我是入门级的。如果有人有意见,请告诉我。 谢谢

【问题讨论】:

  • 我不明白。附加条件不是很明显吗?您对这个问题有什么困惑?

标签: sql oracle


【解决方案1】:

您可以将条件添加到子查询中:

SELECT t1.customer, t1.type, t1.product
FROM yourTable t1
WHERE EXISTS (SELECT 1
              FROM yourTable t2
              WHERE t2.customer = t1.customer AND
                    t2.type = 'a' AND
                    t2.product = 1
             );

如果您只想要客户:

select customer
from yourtable
group by customer
having sum(case when type = 'a' and product = 1 then 1 else 0 end) > 0;

【讨论】:

  • 谢谢你的回复,我想知道我可以先select product =1,然后申请where exists。因为where exists 似乎需要很长时间才能实现......谢谢
  • @Heisenberg 。 . .对于性能,您需要在(customer, type, product) 上建立索引,但您的问题中没有提到性能。
【解决方案2】:

这是根据您的要求的版本

WITH CTE_yourTable AS
(
SELECT CUSTOMER
FROM yourTable
WHERE 
type = 'a' AND
product = 1)
SELECT t1.customer, t1.type, t1.product
FROM yourTable t1
WHERE EXISTS (SELECT 1
              FROM CTE_yourTable t2
              WHERE t2.customer = t1.customer 
             );

【讨论】:

    猜你喜欢
    • 2022-01-24
    • 1970-01-01
    • 2012-05-20
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多