2015-05-25 189 views
0

如何計算位於同一個表格中的兩組數據之間的添加,刪除和修改?這裏有一個例子:在單個表格上計算增量

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的名字變成了羅伯特,克里斯已被刪除,丹尼斯已添加。

到目前爲止,我可以得到補充:

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; 

但我不知道怎麼去修改。

有沒有更好的方法?

謝謝

回答

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; 

最後並沒有那麼糟糕。

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