如何在'NOT Equal'条件下查询多个

问题描述 投票:1回答:3

我试图找出如何拉回记录,其中“字段A”和“字段B”不能是一组设置。

示例:字段A不能等于“已调度”,而字段B等于“已预定”

但我确实想看到其他记录,其中字段A =“已安排”,字段B =“已预定”

我希望这是有道理的,请看下面的脚本,我已经包含了一个非常基本的临时表,其中包含了我想要实现的示例,我有一个使用CONCAT的解决方法,但我不认为这是最好的解决方案?

我知道我可以通过做一个不存在的地方来排除这些,但在实际的数据库中,这将是一个大表,我宁愿不加倍查询。

我也有一个解决方法,但我想知道是否有一个正确/更好的方法来完成这项任务。

请参阅代码和评论。

    --=============================
-- Create Table
--=============================
CREATE TABLE #Temp
(
[id] INT IDENTITY(1,1),
[status] nvarchar(100),
[fkstatus] NVARCHAR(200),
[Date] DATE
)

--=============================
-- Insert Into Table
--=============================
INSERT INTO [#Temp]
(
    [status],
    [fkstatus],
    [Date]
)
VALUES
(N'Scheduled',  N'PreliminaryScheduled', GETDATE()), (N'Scheduled',  N'PreliminaryScheduled', '2019-01-01'), (N'Cancelled',  N'PreliminaryScheduled', '2019-02-01'), (N'Complete',  N'PreliminaryScheduled', GETDATE()), (N'Scheduled',  N'Other', '2019-03-01')

--=============================
--(A)
-- Brings back what I DO NOT want, these are the items that I want to exclude.
--=============================
SELECT * 
FROM [#Temp]
WHERE ([status] = 'Scheduled'  AND [fkStatus] = 'PreliminaryScheduled')

--=============================
-- (B)
-- Real world logic, I beleive this should work?.....
--=============================
SELECT * 
FROM [#Temp]
WHERE ([status] <> 'Scheduled' AND [fkStatus] <> 'PreliminaryScheduled')

--=============================
-- (C)
-- Work Around - Or is this the actual way this has to be done?
--=============================
SELECT * 
FROM [#Temp]
WHERE CONCAT([status],'-',[fkstatus]) <> 'Scheduled-PreliminaryScheduled'

--=============================
-- (D)
-- Additional with a Date.
--=============================
SELECT * 
FROM [#Temp]
WHERE  ([status] <> 'Scheduled' or [fkStatus] <> 'PreliminaryScheduled')
AND [Date] < '2019-01-01'

- 我希望这能从点(C)返回结果,但考虑到(D)。

sql sql-server where-clause
3个回答
2
投票

您可以尝试使用OR而不是AND

SELECT * 
FROM [#Temp]
WHERE  ([status] <> 'Scheduled' or [fkStatus] <> 'PreliminaryScheduled')

1
投票

使用NOT否定您不希望记录满足的条件:

SELECT * FROM #temp 
WHERE NOT ([status] = 'Scheduled'  AND [fkStatus] = 'PreliminaryScheduled')

或者,使用OR

SELECT * FROM #temp 
WHERE [status] <> 'Scheduled'  OR [fkStatus] <> 'PreliminaryScheduled'

它们都导致相同的查询计划(使用OR),您可能会发现第一个更清晰一点。


1
投票

您可以使用NOT语句。

SELECT * FROM [#Temp]
    WHERE [Date] < '2019-01-01'
        AND NOT ([status] = 'Scheduled'  AND [fkStatus] = 'PreliminaryScheduled')
© www.soinside.com 2019 - 2024. All rights reserved.