计算单个表的增量

时间:2015-05-25 10:30:11

标签: sql database

如何计算位于同一个表中的两组数据之间的添加,删除和修改?这是一个例子:

drop table if exists people;
create table people (job int, id int, name varchar(255));

insert into people values (1, 1, "Amy");
insert into people values (1, 2, "Bob");
insert into people values (1, 3, "Chris");

insert into people values (2, 1, "Amy");
insert into people values (2, 2, "Robert");
insert into people values (2, 4, "Dennis");

在这个例子中,Bob的名字已经改为Robert,Chris已被删除,Dennis已被添加。

到目前为止,我可以得到补充:

select p2.* from people p1
right join people p2
on p1.job = 1
and p2.job = 2
and p1.id = p2.id
where p2.job = 2
and p1.id is null;

我可以得到删除:

select p1.* from people p1
left join people p2
on p1.job = 1
and p2.job = 2
and p1.id = p2.id
where p1.job = 1
and p2.id is null;

但我不确定如何进行修改。

有更好的方法吗?

由于

2 个答案:

答案 0 :(得分:1)

对于示例数据,这将返回已修改的

select * from people p1
join people p2
on p1.job = 1 
and p2.job = 2
and p1.id = p2.id         -- same id
WHERE p1.name <> p2.name  -- but different name

答案 1 :(得分:0)

我设法搞清楚了!

select * from people p1
join people p2
on p1.job = 1
and p2.job = 2
and p1.id = p2.id
where p1.name != p2.name;

最终它并不是那么糟糕。