Re: [SQL ] 請問能否刪除某欄位重複的資料?
※ 引述《kusoayan (瑋哥)》之銘言:
: DB是 MySQL
: ...
: 想請問的是,有沒有什麼 SQL 語法可以刪除整張table中 kid 重複的資料?
: 例如
: id / kid / type :
: 1 / 15 / A
: 2 / 16 / B
: 3 / 15 / C
: 4 / 17 / D
: 有什麼方法可以把 C 刪掉嗎?
: 因為有可能有很多筆都重複…
可以利用 delete 配合 self-join,符合 on 條件式的資料即可刪除。
下列的指令是假設您想刪除的是「kid 重複,但 id 編號比較大」的資料:
use test;
drop table if exists test;
create table test
(
id int,
kid int,
type char(1)
);
insert into test values
(1, 15, 'A'), (2, 16, 'B'), (3, 15, 'C'),
(4, 17, 'D'), (5, 15, 'E'), (6, 16, 'F');
-- 刪除「kid 重複,但 id 編號比較大」的資料:
delete test from test join test R on (test.kid = R.kid and test.id > R.id);
select * from test;
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.38.73.90
→
02/03 20:54, , 1F
02/03 20:54, 1F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):