【问题标题】:Select from table 1 unless there is a relationship in 2 other tables从表 1 中选择,除非在其他 2 个表中存在关系
【发布时间】:2021-08-15 05:47:56
【问题描述】:

我需要从 Officials 表中查询一个姓名,但如果此人的日期被屏蔽,则排除该姓名。

例如,如果 Sam 屏蔽了 2021 年 8 月 21 日和 2021 年 9 月 11 日,如果从 Games 表中选择了相应的日期,则不应选择他。但是,如果选择了 2021 年 9 月 18 日,Sam 应该会出现。我有 3 张桌子:

Officials tbl
RefId      Name
---------------------  
1          Jack
2          Sam
3          Jane

Games tbl                           Blocks tbl
GameId    GameDate               BlockId    RefId    BlockDate
-------------------------        ----------------------
1         8/21/2021               1         2       8/21/2021
2         9/11/2021               2         2       9/11/2021
3         9/18/2021               3         3       8/21/2021 

Desired Output
----------------------------------
If Game 1 is selected: Jack
If Game 2 is selected: Jack and Jane 
If Game 3 is selected: Jack, Sam and Jane

唯一相关的 2 个表是 Officials 表和 Blocks 表,带有 RefId。我需要将 BlockDate of Blocks 表与 GameDate of Games 表进行比较。我尝试了一些 sql 语言,这显然是不正确的,但我正在寻找一种方法来完成我想做的事情:

@GameDate datetime,

Select c.Id, c.Name 
From Officials c 
Where In c.Id And Blocks.BlockDate <> Games.GameDate)

【问题讨论】:

    标签: sql sql-server tsql


    【解决方案1】:

    您可以使用NOT EXISTS

    SELECT o.*
    FROM Officials o
    WHERE NOT EXISTS (
      SELECT 1
      FROM Blocks b INNER JOIN Games g
      ON g.GameDate = b.BlockDate
      WHERE b.RefId = o.RefId AND g.GameId = ?
    );
    

    请参阅demo

    【讨论】:

      猜你喜欢
      • 2015-11-03
      • 2020-03-25
      • 2014-03-12
      • 1970-01-01
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多