admin

SQL-至少排除一次满足要求的列的值

sql

有两个表ClientStock

Table Client
    Column IDC       (primary key, int, not null)

Table Stock
    Column IDS       (primary key, int, not null)
    Column IDC       (int, not null)
    Column Type      (bit, not null)
    Column Price     (decimal(10,2), null)

它们应被视为由连接Client.IDC = Stock.IDC

IDC通过Type = 1和获得客户Price not NULL是微不足道的。但是,获得剩余的清单对我来说并不简单IDC。以下尝试未提供正确的清单IDC

SELECT [Client].[IDC]
FROM [Client] LFEFT JOIN [Stock] on [Client].[IDC] = [Stock].[IDC]
WHERE NOT([Stock].[Type] = 1 AND [Stock].[Price] IS NOT NULL)

该语句返回一些IDC应该排除的值,因为对于它们来说,确实存在Type = 0Type = 1和的行,但还有与和的其他行Price not NULL。我应该如何着手获得IDC不具有一行Type = 1,并Price not NULL在所有?


阅读 193

收藏
2021-07-01

共1个答案

admin

ON子句中移动条件。

这意味着该ON子句中的条件将在Stock与连接之前过滤表中的行Client

SELECT [Client].[IDC]
FROM [Client] 
     LEFT JOIN [Stock] 
         on [Client].[IDC] = [Stock].[IDC]
              AND [Stock].[Type] = 1 
              AND [Stock].[Price] IS NOT NULL
WHERE [Stock].[IDC] IS NULL

这也可以使用 NOT EXISTS

SELECT [Client].[IDC]
FROM [Client] c
WHERE NOT EXISTS
(
    SELECT 1
    FROM [Stock] s
    WHERE c.[IDC] = s.IDC
              AND s.[Type] = 1 
              AND s.[Price] IS NOT NULL
)
2021-07-01