1

我有两个具有相同列名和相同复合主键的表。两个表的复合主键是 id + year。我想始终使用表 T1 中的数据,如果表 T2 中存在 id + year,那不在表 T1 中,我希望它也被返回。

这是我的桌子

T1

id  |  year  |  cost
----+--------+-------
1   |  2012  |  1.01
2   |  2012  |  1.02
2   |  2013  |  1.03

T2

id  |  year  |  cost
----+--------+-------
1   |  2012  |  2.01
2   |  2013  |  2.02
3   |  2013  |  2.03

我想得到:

id  |  year  |  cost
----+--------+-------
1   |  2012  |  1.01
2   |  2013  |  1.02
2   |  2013  |  1.03
3   |  2013  |  2.03

这显然是错误的,但我试过:

SELECT
  T1.id,
  T1.year,
  T1.cost
FROM employee_cost AS T1
  INNER JOIN (select
        employee_cost_historic.id,
        employee_cost_historic.year,
        employee_cost_historic.cost
          from employee_cost_historic) AS T2
    ON T1.id = T2.id
      AND T1.year = T2.year
4

2 回答 2

2

或者使用 LEFT JOIN 和 IS NULL 的另一个选项:

SELECT T1.Id, T1.Year, T1.Code
FROM T1 
UNION
SELECT T2.Id, T2.Year, T2.Code
FROM T2
  LEFT JOIN T1 ON T1.Id = T2.Id AND T1.Year = T2.Year
WHERE T1.Id IS NULL

祝你好运。

于 2013-01-31T19:28:14.953 回答
1

您可以使用以下命令执行此操作union all

select id, YEAR, cost
from t2
union all
select id, YEAR, cost
from t2
where not exists (select 1 from t1 where t1.id = t2.id and t1.year = t2.year)
于 2013-01-31T19:23:24.223 回答