teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

sample

2017/10/12 08:19

投稿

yambejp
yambejp

スコア117912

answer CHANGED
@@ -5,4 +5,55 @@
5
5
  GROUP BY first_name_kana,last_name_kana,phone_number,city
6
6
  HAVING count(*)>1
7
7
  ```
8
- とするだけでよいかと思います
8
+ とするだけでよいかと思います
9
+
10
+ # sample
11
+
12
+ ```SQL
13
+ create table nayose_otameshi(id int primary key auto_increment,
14
+ first_name_kana varchar(10),
15
+ last_name_kana varchar(10),
16
+ phone_number varchar(10),
17
+ city varchar(10));
18
+
19
+ insert into nayose_otameshi(first_name_kana,last_name_kana,phone_number,city) values
20
+ ('f1','l1','p1','c1'),
21
+ ('f2','l2','p2','c2'),
22
+ ('f2','l2','p2','c2'),
23
+ ('f3','l3','p3','c3'),
24
+ ('f1','l4','p4','c4'),
25
+ ('f1','l1','p1','c1'),
26
+ ('f3','l3','p3','c3'),
27
+ ('f2','l2','p2','c2');
28
+ ```
29
+ 上記のように別途主キーが設定されているのであれば2番め以降に出て来るレコードはこう
30
+ ```SQL
31
+ select id from nayose_otameshi as t1
32
+ where exists(select 1 from nayose_otameshi as t2
33
+ where 1
34
+ and t1.first_name_kana=t2.first_name_kana
35
+ and t1.last_name_kana=t2.last_name_kana
36
+ and t1.phone_number=t2.phone_number
37
+ and t1.city=t2.city
38
+ and t1.id>t2.id
39
+ )
40
+ ```
41
+ id=3,6,7,8が抽出されるのでこれを利用して削除
42
+ ```SQL
43
+ delete from nayose_otameshi
44
+ where id in(
45
+ select id from(
46
+ select id from nayose_otameshi as t1
47
+ where exists(select 1 from nayose_otameshi as t2
48
+ where 1
49
+ and t1.first_name_kana=t2.first_name_kana
50
+ and t1.last_name_kana=t2.last_name_kana
51
+ and t1.phone_number=t2.phone_number
52
+ and t1.city=t2.city
53
+ and t1.id>t2.id
54
+ )
55
+ )as temp
56
+ )
57
+ ```
58
+ deleteに自己結合したデータはダイレクトにつかえないので
59
+ 一度ダミーのサブクエリでselectを抽出しないといけません