简体   繁体   English

将具有两个不同列的两个相似表联接起来

[英]Join two similar tables with some different columns

We have two tables, one showing results from a process and one showing errors or other events. 我们有两个表,一个表显示流程的结果,另一个表显示错误或其他事件。 Some of the columns can be combined, while others can't. 有些列可以合并,而另一些则不能。 There are unique columns in each table, so I can't use a UNION ALL. 每个表中都有唯一的列,所以我不能使用UNION ALL。

For example I have the following columns (there are more but you get the idea): 例如,我有以下几列(还有更多专栏,但您明白了):

EventID | DateTime | Station | ErrMsg

ResultID | DateTime | Station | MatNum | SerialNum

So the first three columns in each example table could be combined, but the others would need their own column. 因此,每个示例表中的前三列可以合并,但其他列则需要自己的列。

The idea here is to overlay the results with the errors and order by the date/time so that we can see if there are any process steps causing errors. 这里的想法是按日期/时间在错误和顺序上覆盖结果,以便我们查看是否有任何导致错误的处理步骤。

I've tried different joins, unions, ect, but didn't quite get what I want. 我尝试了不同的联接,联合等,但并没有得到我想要的。

Any thoughts? 有什么想法吗?

This would technically work, if this is really how you want to have your output... 如果这确实是您希望获得输出的方式,则从技术上讲这是可行的...

Select
EventID, DateTime, Station, ErrMsg, NULL
from Events
UNION ALL
Select
ResultID, DateTime, Station, MatNum, SerialNum
from Results

Since the first three columns have compatible data types and the others don't you'l need to separate columns for each of the incompatible columns. 由于前三列具有兼容的数据类型,而其他三列则不具有,因此您需要为每个不兼容的列单独分隔列。 I'd also add a discriminator column so you can immediately tell which data source the row came from: 我还将添加一个鉴别符列,以便您可以立即知道该行来自哪个数据源:

Select
'E' src, EventID,  DateTime, Station, NULL,   NULL,      ErrMsg
from Events
UNION ALL
Select
'R' src, ResultID, DateTime, Station, MatNum, SerialNum, NULL
from Results

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM