【问题标题】:Select Customers where not have value in other table with join通过连接选择在其他表中没有价值的客户
【发布时间】:2018-06-26 10:59:36
【问题描述】:

我需要从表 Customer 中选择所有 Customers,其中表 Customer_Value 中的 Value 不是 4。 客户:

 +------------+-------+
 | Customer   | ...   |
 +------------+-------+
 | 312        | ...   |
 | 345        | ...   |
 | 678        | ...   |
 +------------+-------+

客户价值:

 +------------+-------+
 | Customer   | Value |
 +------------+-------+
 | 312        | 1     |
 | 312        | 2     |
 | 345        | 1     |
 | 345        | 2     |
 | 345        | 3     |
 | 678        | 1     |
 | 678        | 2     |
 | 678        | 4     |
 +------------+-------+

为了得到我的结果,我使用了以下查询:

SELECT C.Customer FROM [Customer] C
Left join Customer_Value V ON (C.Customer = V.Customer)
WHERE C.Customer NOT IN (SELECT Customer FROM [Customer_Value] WHERE Value = '4')
GROUP BY C.Customer

所以我的问题是:

这是一个快速而好的查询吗?还是有其他更好的解决方案来获取所有客户 ID?

【问题讨论】:

  • 请在标签中指定您使用的数据库

标签: sql sql-server join database-performance


【解决方案1】:

您可以在 where 条件中使用 Left Join 和 IS NULL Filter 来避免负条件。

SELECT C.Customer FROM [Customer] C
Left join Customer_Value V ON (C.Customer = V.Customer) and V.Value = '4'
WHERE V.Value is null
GROUP BY C.Customer

【讨论】:

  • LEFT JOIN 是否定运算符的最佳解决方案,如果删除否定运算符,查询性能会更好。
【解决方案2】:

你的方法太过分了; JOIN 不是必需的。我会使用not exists:

select c.Customer 
from Customer c
where not exists (select 1
                  from customer_value cv
                  where c.Customer = v.Customer and
                        cv.value = 4
                 );

如果您假设所有客户在customer_value 中至少有一行,您也可以使用聚合:

select cv.customer
from customer_value cv
group by cv.customer
having sum(case when cv.value = 4 then 1 else 0 end) = 0;

【讨论】:

    【解决方案3】:

    我愿意

    select * from customer c
    join (
    select distinct customer from customer_value where value!=4) v on c.customer = v.customer
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-12
      • 1970-01-01
      • 2014-04-24
      • 2017-10-05
      • 2020-04-12
      • 2021-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多