重複する redords を含むテーブルがあります。ユニークなレコードを作りたい。新しいテーブル (宛先など) を作成し、その中に一意の列を指定しました。table1 (ソース) からレコードをコピーして、レコードが宛先テーブルに挿入された場合に再度挿入しないようにする方法を教えてください。
3 に答える
1
次のように、「 select into 」構文を使用して、個別の行のみを選択して挿入できます。
insert into table_without_dupes (column0, column1) select distinct column0, column1 from table_with_dupes
行を区別する自動インクリメントまたはその他の列がある場合は、それらをステートメントの挿入および選択部分から除外することができます。
編集:
単一の列で重複を検出する場合は、group by を使用できます。
insert into table_without_dupes (column0, column1) select column0, column1 from table_with_dupes group by column0
MySQL では、select で集計されていない列を参照できますが、ドキュメントには「サーバーは各グループから任意の値を自由に選択できる」と記載されていることに注意してください。グループの特定の行を 1 つ選択する場合は、次の例を見つけることができます。使える。
于 2012-07-20T08:56:17.670 に答える
1
一般的なアプローチ
insert into destination(col1,col2)
select DISTINCT col1,col2 from source as s where not exists
(select * from destination as d where d.col1=s.col1)
編集済み
insert into destination(col1,col2)
SELECT distinct col1,col2 from source
編集済み (col3 が複製されており、そのコピーが 1 つだけ必要であると仮定します。)
insert into destination(col1,col2,col3,....,colN)
SELECT col1,col2,col3,...,colN from source as s1 inner join
(
select col1,col2,max(col3) as col3
from source
group by col1,col2
) as s2 on t1.col1=t2.col1 and t1.col2=t2.col2 and t1.col3=t2.col3
于 2012-07-20T08:57:27.243 に答える
0
insert into <dest_table_name>
select distinct * from <source_table_name>;
于 2012-07-20T09:01:11.993 に答える