建表,插入資料,當然如果你不想測試一下,也可以直接用後面的刪除語句
create table if not exists `tb01` (
`id` int unsigned primary key auto_increment,
`name` varchar (10) not null
);insert into `tb01` (`name`)
values
('zhangsan'),
('lisi'),
('wangwu'),
('zhangsan'),
('lisi'),
('wangwu'),
('zhaoliu'),
('wangwu');
查詢
mysql>
select
*from tb01;
+----+----------+
| id | name |
+----+----------+|1
| zhangsan ||2
| lisi ||3
| wangwu ||4
| zhangsan ||5
| lisi ||6
| wangwu ||7
| zhaoliu ||8
| wangwu |
+----+----------+
8rows
inset
(0.01 sec)
刪除語句
# 用法:
delete
from
`表名`
where
`主鍵名`
notin
(select
`主鍵名`
from
(select
`主鍵名`
from
`表名`
group
by`重複字段`)`
temp`)
;# 例項:
mysql>
delete
from
`tb01`
where
`id`
notin
(select
`id`
from
(select
`id`
from
`tb01`
group
by`name`)`
temp`)
;query ok,
4rows affected (
0.01 sec)
你或許有疑問為什麼不這樣寫呢:
delete
from
`tb01`
where
`id`
notin
(select
`id`
from
`tb01`
group
by`name`
)
試一下吧
mysql>
delete
from
`tb01`
where
`id`
notin
(select
`id`
from
`tb01`
group
by`name`);
error 1093
(hy000): you can't specify target table 'tb01' for
update
infrom clause
在同一條sql語句中,不能先查出這個表的某個值,又去修改這個表,所以要倒騰一下。
再次查詢,重複的已經刪除
mysql>
select
*from tb01;
+----+----------+
| id | name |
+----+----------+|1
| zhangsan ||2
| lisi ||3
| wangwu ||7
| zhaoliu |
+----+----------+
4rows
inset
(0.00 sec)
mysql刪除重複資料
最近遇到刪除重複資料的問題,先分享一下解決辦法,如有不完善之處還望包涵!舉例如下 mysql select from table03 id name degree 1 fly 90 2 fly 90 3 fly 90 4 fly 80 5 wang 90 6 wang 90 7 wang 90 8 ...
mysql刪除重複資料
id 姓名 課程名稱 分數 1 張三 數學 69 2 李四 數學 89 3 張三 數學 69 刪除除了自動編號不同,其他都相同的學生冗餘資訊 完整的sql語句如下 delete from tablename where id not in select bid from select min id ...
刪除重複資料
介紹兩種刪除重複行的方式 1.使用臨時表,分組找出重複部分的id進行刪除 刪除table goods info 中存在重複goods id的記錄 select identity int,1,1 as autoid,into temptable from goods info select min a...