sql - 删除具有两个相同列值的行

时间:2017-04-22 23:17:48

标签: sql union

表1

Comparator

表2

|-------------------------------|
| empid   |  scheddate| schedule|
|-------------------------------|
|   1     |2017-04-21 |  null   |
|-------------------------------|
|   1     |2017-04-22 |  null   |
|-------------------------------|
|   1     |2017-04-23 |  null   |
|-------------------------------|
|   1     |2017-04-24 |  null   |
|-------------------------------|
|   1     |2017-04-25 |  null   |
|-------------------------------|
|   1     |2017-04-26 |  null   |
|-------------------------------|
使用

|-------------------------------|
| empid   |  scheddate| schedule|
|-------------------------------|
|   1     |2017-04-21 |  8-5    |
|-------------------------------|
|   1     |2017-04-22 |  8-5    |
|-------------------------------|
|   1     |2017-04-23 |  8-5    |
|-------------------------------|
|   2     |2017-04-21 |  8-5    |
|-------------------------------|
|   2     |2017-04-22 |  8-5    |
|-------------------------------|
|   2     |2017-04-23 |  8-5    |
|-------------------------------|

我有

表3

insert into table3 
select * from table1 union select * from table2

我想知道如何得到像这样的结果

|-------------------------------|
| empid   |  scheddate| schedule|
|-------------------------------|
|   1     |2017-04-21 |  null   |
|-------------------------------|
|   1     |2017-04-22 |  null   |
|-------------------------------|
|   1     |2017-04-23 |  null   |
|-------------------------------|
|   1     |2017-04-24 |  null   |
|-------------------------------|
|   1     |2017-04-25 |  null   |
|-------------------------------|
|   1     |2017-04-26 |  null   |
|-------------------------------|
|   1     |2017-04-21 |  8-5    |
|-------------------------------|
|   1     |2017-04-22 |  8-5    |
|-------------------------------|
|   1     |2017-04-23 |  8-5    |
|-------------------------------|
|   2     |2017-04-21 |  8-5    |
|-------------------------------|
|   2     |2017-04-22 |  8-5    |
|-------------------------------|
|   2     |2017-04-23 |  8-5    |
|-------------------------------|

1 个答案:

答案 0 :(得分:0)

你似乎想要这个逻辑:

insert into table3 (empid, scheddate, schedule) -- should always list columns 
    select empid, scheddate, schedule
    from table1 t1 
    where not exists (select 1 from table2 t2 where t2.empid = t1.empid and t2.scheddate = t1.scheddate)
    union all
    select empid, scheddate, schedule
    from table2;