我有一个表,我想用新日期插入旧值,但只插入唯一的值。
t1
ID | Block | Flats |
1 | 1 | GF-1 |
2 | 1 | GF-2 |
3 | 2 | GF-1 |
4 | 2 | GF-2 |
5 | 2 | GF-2 |这是我表的一部分,我希望它在复制后成为一些示例数据。
ID | Block | Flats |
1 | 1 | GF-1 |
2 | 1 | GF-2 |
3 | 2 | GF-1 |
4 | 2 | GF-2 |
5 | 2 | GF-2 |
6 | 1 | GF-1 |
7 | 1 | GF-2 |
8 | 2 | GF-1 |
9 | 2 | GF-2 |由于复制后,它只复制不同的值,而GF-2只出现一次。但当我试着
insert into t1 (ID,Block,Flats) select distinct Block,Flats from t1它在第2块中复制了两次GF-2。
注意: ID列自动递增1。
发布于 2017-05-05 14:13:09
您可以使用cross join生成所有行,然后清除已经存在的行:
insert into t1(block, flats)
select b.block, f.flats
from (select distinct block from t1) b cross join
(select distinct flats from t1) f left join
t1
on t1.block = b.block and t1.flats = f.flats
where t1.block is null;注意:这假设id是一个identity列(我看到您已经描述为是这样的)。
https://stackoverflow.com/questions/43806696
复制相似问题