Oracle SQL查询的问题

Oracle SQL查询的问题,sql,oracle,Sql,Oracle,这是我的示例数据结构和示例数据。我在这里试图做到的是,不向拥有“订户”类型的订户记录的客户显示。您将在数据集中看到Eli Manning有两个订阅记录。一个是“所有者”类型,另一个是“订户”类型。因此,他不应该出现在我的结果中,因为有一个“订户”记录实例。小奥德尔·贝克汉姆只有一张“拥有者”类型的唱片,所以他应该表现出来 我曾尝试使用此查询,但结果返回客户Saquan Barkley。您将看到,该客户在Subscribers表中有一个“Subscriber”记录,因此我的sql没有按预期工作。任

这是我的示例数据结构和示例数据。我在这里试图做到的是,不向拥有“订户”类型的订户记录的客户显示。您将在数据集中看到Eli Manning有两个订阅记录。一个是“所有者”类型,另一个是“订户”类型。因此,他不应该出现在我的结果中,因为有一个“订户”记录实例。小奥德尔·贝克汉姆只有一张“拥有者”类型的唱片,所以他应该表现出来

我曾尝试使用此查询,但结果返回客户Saquan Barkley。您将看到,该客户在Subscribers表中有一个“Subscriber”记录,因此我的sql没有按预期工作。任何帮助都将不胜感激

我的问题是:

select distinct
    a.customer_id,
    a.fst_name,
    a.last_name,
    a.email,
    b.subscription_type
from
    customers a,
    subscriptions b
where
    a.customer_id <> (select customer_id from subscriptions
                      where subscription_type <> 'SUBSCRIBER')
    AND b.subscription_type <> 'SUBSCRIBER'
order by customer_id asc;

请尝试以下代码:

  SELECT a.customer_id, a.fst_name, a.last_name, a.email, b.subscription_type
    FROM customers a 
    LEFT JOIN subscriptions b ON (b.customer_id = a.customer_id)
   WHERE a.customer_id NOT IN (SELECT customer_id
                                 FROM subscriptions
                                WHERE subscription_type = 'SUBSCRIBER')
ORDER BY a.customer_id ASC;

除了将代码更改为include NOT IN而不是include IN,然后将子查询条件更改为包含所有类型中具有“SUBSCRIBER”类型的客户之外,我还将语法更改为使用显式联接。除此之外,如果正确地联接表,则不需要使用DISTINCT。

您的查询接近您想要的查询,而不是使用try not in,子查询可能会返回多行,您无法对其应用

例:


你是说像这样的

    select distinct a.customer_id, a.fst_name, a.last_name, a.email,
                b.subscription_type
  from customers a, subscriptions b
 where a.customer_id = b.customer_id 
   and a.customer_id not in (select customer_id from subscriptions
    where subscription_type = 'SUBSCRIBER')
 order by customer_id asc

今天的提示:切换到现代的显式连接语法。更容易编写而不出错,更容易阅读和维护,并且在需要时更容易转换为外部联接。另一个技巧:使用有意义的表别名,如“客户”的“c”。订阅b不是来自客户a的a、b等,而是来自客户a的交叉连接订阅b。您没有应用任何关于如何联接这两个表的标准,例如a.customer\u id=b.customer\u id。因此,您将所有客户与所有订阅合并。你真的不应该使用这种语法。在标准SQL1992中,它被显式联接所取代,尽管Oracle花了九年时间才最终在Oracle9i中采用它。DISTINCT是写得不好的查询的典型标志。与其马上应用它,不如考虑一下它的用途。输出中是否需要b.u类型?这当然会导致同一客户的多行。若您需要它,难道您不希望列表是一个逗号分隔的字符串,其中包含类型,每个客户只有一行吗?如果您不需要它,那么您根本不必加入subscriptions表。
select distinct
    a.customer_id,
    a.fst_name,
    a.last_name,
    a.email,
    b.subscription_type
from
    customers a
    inner join subscriptions b on a.customer_id = b.customer_id
where b.subscription_type <> 'SUBSCRIBER' 
and a.customer_id not in
(
  select customer_id from subscriptions where subscription_type = 'SUBSCRIBER'
)
order by customer_id asc;
    select distinct a.customer_id, a.fst_name, a.last_name, a.email,
                b.subscription_type
  from customers a, subscriptions b
 where a.customer_id = b.customer_id 
   and a.customer_id not in (select customer_id from subscriptions
    where subscription_type = 'SUBSCRIBER')
 order by customer_id asc