【问题标题】:Exclude one item with different corelated value in the next column SQL在下一列 SQL 中排除具有不同相关值的项目
【发布时间】:2022-01-18 05:47:18
【问题描述】:

我有两张桌子:

acc_num ser_code
1 A
1 B
1 C
2 C
2 D

第二个是:

ser_code value
A 5
B 8
C 10
D 15

我想排除服务代码值为 10 或 15 的所有帐户。 因为我的数据集很大,我想使用 NOT EXIST 但它只是排除了 acc_num 和 ser_code 的组合。 我想用所有的 ser_code 排除 acc_num,因为它的 ser_code 符合我的标准。

我用过:
选择 acc_num, ser_code
从表 1
不存在的地方(选择 1
FROM 表 2 其中 acc_num = acc_num 和 (10, 15) 中的值

上面的代码输出是:

acc_num ser_code
1 A
1 B

输出的愿望是空的。

【问题讨论】:

  • 您使用的是哪个 rdms?
  • Oracle 和 Microsoft SQL Server 数据库
  • select distinct acc_num from table2 where value in (10, 15) 是否返回您要过滤掉的 acc_num?然后很容易将其合并到您的查询中:where acc_num not in (select distinct acc_num from table2 where value in (10, 15))

标签: sql not-exists exclude


【解决方案1】:

这可以通过多种方式实现。但是使用NOT EXISTS 是最好的选择。您查询的问题是acc_num 1,有ser_code 的值不为10、15。因此您将在结果中得到AB

要克服这个问题,您必须将acc_num 拉入sub-query

查询 1(使用 NOT EXISTS):

正如您在下面的查询中看到的,我在sub-query 中包含了acc_num,以便过滤器正常工作,

SELECT DISTINCT a.acc_num, a.ser_code 
FROM one as a
WHERE NOT EXISTS
       (
       SELECT DISTINCT one.acc_num 
       FROM two 
       INNER JOIN one
           ON one.ser_code=two.ser_code
       WHERE value IN (10,15) AND a.acc_num=one.acc_num
       )

查询 2(使用 LEFT JOIN):

NOT EXISTS 由于其性质而经常令人困惑(尽管是超级 fast)。因此LEFT JOIN也可以使用(比NOT EXISTS贵),

SELECT DISTINCT a.acc_num, a.ser_code 
FROM one as a
LEFT JOIN 
       (
       SELECT DISTINCT one.acc_num 
       FROM two 
       INNER JOIN one
           ON one.ser_code=two.ser_code
       WHERE value IN (10,15)
       ) b
   ON a.acc_num=b.acc_num
WHERE b.acc_num IS NULL

查询 3(使用 NOT IN):

NOT IN 也可以通过综合查询来实现这一点,但比上述两种方法都贵,

SELECT DISTINCT a.acc_num, a.ser_code 
FROM one as a
WHERE a.acc_num NOT IN
       (
       SELECT DISTINCT one.acc_num 
       FROM two 
       INNER JOIN one
           ON one.ser_code=two.ser_code
       WHERE value IN (10,15)
       )

所有 3 个都会产生相同的结果。我宁愿选择 NOT EXISTS

db<>fiddle

中查看有关时间消耗的演示

【讨论】:

    【解决方案2】:

    你来了

    select t1.acc_num,t1.ser_code from table1 t1, table2 t2 
    where (t1.ser_code=t2.ser_code and  t2.value not in (10,15)) 
    and t1.acc_num  not in 
    (
        select t3.acc_num from table1 t3,table2 t4 
        where t1.acc_num=t3.acc_num and t3.ser_code=t4.ser_code 
        and  t4.value  in (10,15)
    ) ;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 2022-11-24
      相关资源
      最近更新 更多