sql - 在表 C 中不存在的表 B 中查找表 A 中缺失的记录

标签 sql sql-server sql-server-2012

我有 3 个表:

Customer (CustomerID)
CustomerEvent (CustomerEventID, CustomerID, EventTypeID)
EventType (EventTypeID)

一些客户记录有一些带有 EventType 的 CustomerEvent 记录,一些客户记录没有 CustomerEvent 记录。

如何为每个客户记录识别/插入每个事件类型的缺失客户事件记录?

我的实际问题比这更详细,但是,这是我正在努力解决的问题。

我可以使用一个选择语句来识别所有缺失的 CustomerEvent 记录吗?或者我是否需要对每个 EventType 记录进行 UNION?

最佳答案

使用cross join生成所有CustomerId,EventTypeId的集合,过滤掉CustomerEvent中存在的,不存在的()

select c.CustomerId, e.EventTypeId
from Customer c
  cross join EventType e
where not exists (
  select 1
  from CustomerEvent ce
  where c.CustomerId = ce.CustomerId
    and e.EventTypeId = ce.EventTypeId
    )

关于sql - 在表 C 中不存在的表 B 中查找表 A 中缺失的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44442973/

相关文章:

sql-server - 如何在 SQL Server 抛出中创建串联消息?

sql-server-2008-r2 - SQL Server 查询时的默认数据库 - master

sql - 具有输出参数的存储过程与表值函数?

sql - 如何搜索SQL表列文本并挑选一个字符串或返回最大数字

sql - 元组关系演算中的员工部门查询和最低和最高工资?

c# - Linq2Sql : How to handle tables with the same name and different schema names

java - executeQuery 方法必须返回结果集问题

visual-studio - Visual Studio 2015 从 SQL Server 2012 LocalDB 迁移数据库 - 登录时出错

java - 在这种特殊情况下,我们应该使用 Java 代码来选择数据还是使用存储过程?

sql - 递归相关表达式如何加速不同的查询?