简体   繁体   English

基于匹配列比较两个SQL表

[英]Comparing Two SQL Tables Based On Matching Column

I have two tables, T1 and T2. 我有两个表,T1和T2。 T1 looks like this: T1看起来像这样:

    ID      Type      Date
    _____________________________
    1       CA        11-17-2018
    2       BA        7-12-2018
    3       CA        4-1-2018
    4       BA        1-17-2018
    5       CA        9-30-2018

And T2 looks like this: T2看起来像这样:

    ID      Type      Date
    _____________________________
    1       CA        11-17-2018
    2       BA        3-1-2018
    3       CA        4-1-2018
    4       CA        1-17-2018
    5       CA        10-3-2018

I need a way to compare rows from the two tables that have matching IDs and see if the other values match or if they're different. 我需要一种方法来比较两个具有匹配ID的表中的行,并查看其他值是否匹配或它们是否不同。 I only want the output table to contain those IDs with differing values, and display those values. 我只希望输出表包含具有不同值的那些ID,并显示这些值。 Thanks in advance. 提前致谢。

Try this: 尝试这个:

SELECT T1.ID, T1.Type as T1Type, T2.Type as T2Type, T1.Date as T1Date, T2.Date as T2Date
FROM T1
INNER JOIN T2
ON T1.ID = T2.ID
WHERE T1.DATE <> T2.DATE
OR T1.Type <> T2.Type

Notice that this query will only return result where the ID is present in both tables. 请注意,此查询将仅返回两个表中都存在ID结果。

I think you need below something, inner join and comparison 我认为您需要以下内容, inner join and comparison

  select T1.*,T2.* from T1 inner join T2 on T1.id=T2.id
    where T1.Type!=T2.Type   and T1.Date!=T2.Date

You would use join : 您将使用join

select t1.*, t2.*
from t1 join
     t2
     on t1.id = t2.id
where (t1.type <> t2.type) or (t1.date <> t2.date)

you can put one foreign key in one of this tables, who will make reference to the other. 您可以在其中一个表中放置一个外键,后者将引用另一个。

When you make a select, you can do a join of one table with other by the primary key and the foreign key. 进行选择时,可以通过主键和外键将一个表与另一个表进行联接。

SELECT column FROM table1 JOIN table2 ON table1.id_pk = table2.id_fk WHERE condition;

in WHERE you put something like 在哪里,你把

WHERE (table1.id != table2.id) OR (table1.type != table2.type) OR (table1.date != table2.date);

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

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