从表中删除另一个中不存在的行

时间:2014-07-10 07:26:53

标签: postgresql-9.1 delete-row

我有两张桌子

表1 --- --- file_id,est_edit_id,cal_head_code,cal_spec_code,cal_item_head_code

表2-- file_id,est_edit_id,cal_head_code,cal_spec_code,cal_item_head_code,cal_item_code

我想从表2中删除与表1中的值(file_id,est_edit_id,cal_head_code,cal_spec_code,cal_item_head_code)不匹配的行

同一个

的任何帮助

例如
表A包含

-----------
file_id |est_edit_id,| cal_head_code| cal_spec_code| cal_item_head_code     
  1     |      2     |      3        |     4        |         5
--

表B包含

file_id   |est_edit_id ,| cal_head_code  | cal_spec_code  |   cal_item_head_code  |cal_item_code   
  1     |      2     |      3        |     4        |         5          | 20
  1     |      2     |      3        |     4        |         5          | 50
  7     |      8     |      9        |     10       |         11         |21

我想删除包含值7的行8 | 9 | 10 |因为7 |来自表B的11 8 | 9 | 10 |表A中没有11表示

1 个答案:

答案 0 :(得分:0)

这应该这样做:

delete from table2 t2
where not exists (select 1
                  from table1 t1
                  where t1.file_id = t2.file_id
                    and t1.est_edit_id = t2.est_edit_id
                    and t1.cal_head_code = t2.cal_head_code
                    and t1.cal_spec_code = t2.cal_spec_code);

这假设没有列包含null值。

SQLFiddle示例:http://sqlfiddle.com/#!15/e9e9b/1