对于这种情况是否需要 FULL OUTER JOIN?
我正在尝试为我正在编写的存储过程找到使用 FULL OUTER JOIN 的替代方法。这是场景。
两个表,其中包含大部分不相关的数据,表示需要发生的事件。事件需要按时间顺序处理,并且两个表都有一个日期时间列。因此,我需要获取一个表,该表充当按日期时间排序的所有这些事件的列表(这两个日期时间列需要混合在一起)。
一个小问题:有时两个表中的事件会相关,在这种情况下,无论日期时间如何,表 A 中的事件都需要先进行。因此,如果 A 有 3 个事件,B 有 3 个事件,但 A 和 B 之间只有一个相关对,我想返回 5 行。如果存在不相关的数据,则会出现 NULL 数据(没关系,我使用 NULL 数据检查来确定下一步要做什么,即处理事件 A 或 B 等)。
目前我所拥有的看起来像这样:
SELECT
CASE
WHEN A.EventDateTime IS NULL THEN B.EventDateTime
ELSE A.EventDateTime
END AS SortDateTime,
A.EventId,
B.EventId,
FROM A FULL OUTER JOIN B
ON A.RelatedData=B.RelatedData
ORDER BY SortDateTime
I'm trying to find an alternative to using a FULL OUTER JOIN for a stored procedure I am writing. Here's the scenario.
Two tables of mostly unrelated data representing events that need to occur. The events need to be processed in chronological order and both tables have a datetime column. So I need to get a single table that acts as a list of ALL these events ordered by datetime (those two datetime columns need to be mixed together).
A small catch: sometimes events from the two tables will be related, and in this case, event from Table A needs to go first regardless of the datetime. So if A has 3 events, and B has 3 events, but there is a single related pair between A and B, I want to return 5 rows. In cases where there is unrelated data, there will be NULL data (and that's ok, I use NULL data checks to determine what to do next, i.e. process event A or B, etc.)
Currently what I have looks something like this:
SELECT
CASE
WHEN A.EventDateTime IS NULL THEN B.EventDateTime
ELSE A.EventDateTime
END AS SortDateTime,
A.EventId,
B.EventId,
FROM A FULL OUTER JOIN B
ON A.RelatedData=B.RelatedData
ORDER BY SortDateTime
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该没问题,
而不是使用 CASE
你可以这样做
,这有点短
That should be fine
also instead of using CASE
you can do this
Which is a little shorter
如果您确实想避免 OUTER JOIN,您可以尝试
上面的
NOT IN
可以写为NOT EXISTS SELECT 1 FROM A WHERE A.RelatedData = B.RelatedData
或如果您的 RDBMS 有首选项(或者相关子查询更适合您的数据集),则为LEFT JOIN ... IS NULL
。If you really want to avoid the OUTER JOIN you might try
The above
NOT IN
in can be written asNOT EXISTS SELECT 1 FROM A WHERE A.RelatedData = B.RelatedData
or asLEFT JOIN ... IS NULL
if your RDBMS has preferences (or if correlated sub-query is better for your dataset).如果两者之间没有确切的关系,我想不出任何其他方法可以执行此操作。
If there is no exact relation between the two, I can't think of any other way you could perform this.