如何连接两个表但只返回不匹配的行?

编程入门 行业动态 更新时间:2024-10-26 23:33:12
本文介绍了如何连接两个表但只返回不匹配的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个看起来像这样的表:

I have two tables which look like this:

T1: ID | Date | Hour | Interval T2: ID | Date | Hour

我基本上需要在它们的 ID、日期和时间匹配时加入这些表.但是,我只想返回表 1 中与表 2 中的结果不匹配的结果.

I basically need to join these tables when their IDs, dates, and hours match. However, I only want to return the results from table 1 that do not match up with the results in table 2.

我知道这看起来很简单,但我遇到的问题是表 1 中有多行与表 2 匹配(任何给定的小时都有多个间隔).我需要返回所有这些间隔,只要它们不在表 2 中的同一小时内.

I know this seems simple, but where I'm stuck is the fact that there are multiple rows in table 1 that match up with table 2 (there are multiple intervals for any given hour). I need to return all of these intervals so long as they do not fall within the same hour period in table 2.

示例数据:

T1: 1 | 1/1/2011 | 1 | 1 1 | 1/1/2011 | 1 | 2 1 | 1/1/2011 | 2 | 1 1 | 1/1/2011 | 2 | 2 T2: 1 | 1/1/2011 | 1

我的预期结果集将是 T1 的最后两行.任何人都可以指出我在正确的轨道上吗?

My expected result set for this would be the last two rows from T1. Can anyone point me on the right track?

推荐答案

SELECT T1.* FROM T1 WHERE NOT EXISTS(SELECT NULL FROM T2 WHERE T1.ID = T2.ID AND T1.Date = T2.Date AND T1.Hour = T2.Hour)

也可以使用 LEFT JOIN 来完成:

It could also be done with a LEFT JOIN:

SELECT T1.* FROM T1 LEFT JOIN T2 ON T1.ID = T2.ID AND T1.Date = T2.Date AND T1.Hour = T2.Hour WHERE T2.ID IS NULL

更多推荐

如何连接两个表但只返回不匹配的行?

本文发布于:2023-10-20 08:57:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1510512.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:但只   不匹配   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!