回答編集履歴

1

調整

2024/03/07 10:20

投稿

yambejp
yambejp

スコア115010

test CHANGED
@@ -1 +1,60 @@
1
1
  データ投入時は制限をかけずに追加して、投入完了後ダブったデータがあったときに新しい方のデータを削除するというのが妥協点かなと
2
+
3
+ # 参考
4
+ ```SQL
5
+ create table user(uid int primary key ,name varchar(10));
6
+ insert into user values(1,'a'),(2,'b'),(3,'c'),(4,'d'); /* ただしuserテーブルは今回は使わない */
7
+
8
+ create table users(gid int not null,uid int not null,sort int not null,unique key (gid,uid),unique key (gid,sort));
9
+ insert into users values
10
+ (1,1,1),
11
+ (1,2,2),
12
+ (2,2,1),
13
+ (2,1,2),
14
+ (3,1,1),
15
+ (3,2,2),
16
+ (4,1,1),
17
+ (4,2,2),
18
+ (4,3,3),
19
+ (5,1,1),
20
+ (5,2,2);
21
+ ```
22
+ というデータを作ったとします。結果こういうデータ
23
+ |gid|uid|sort|
24
+ |--:|--:|--:|
25
+ |1|1|1|
26
+ |1|2|2|
27
+ |2|2|1|
28
+ |2|1|2|
29
+ |3|1|1|
30
+ |3|2|2|
31
+ |4|1|1|
32
+ |4|2|2|
33
+ |4|3|3|
34
+ |5|1|1|
35
+ |5|2|2|
36
+
37
+ 上記1と3と5がダブっていることがわかります。
38
+ したがってあとから追加した3と5を探す必要があります
39
+
40
+ ```SQL
41
+ select gid,group_concat(uid order by sort) as uids ,rank() over(partition by group_concat(uid order by sort) order by gid ) as r from users group by gid
42
+ ```
43
+ |gid|uids|r|
44
+ |--:|--:|--:|
45
+ |1|1,2|1|
46
+ |3|1,2|2|
47
+ |5|1,2|3|
48
+ |4|1,2,3|1|
49
+ |2|2,1|1|
50
+
51
+ 上記からこうすると削除されます
52
+ ```SQL
53
+ delete from users where gid in(
54
+ select gid from(
55
+ select gid,group_concat(uid order by sort) as uids ,rank() over(partition by group_concat(uid order by sort) order by gid ) as r from users group by gid
56
+ ) as sub where r>1
57
+ );
58
+ ```
59
+
60
+