我有一张桌子
f1|f2|fk 1 | 0|100 1 | 1|200 1 | 2|300 1 | 3|400 2 | 0|300 2 | 1|400 2 | 2|500
(f1,f2)PK在哪里,fk是外键。fk的值并不多,大约20。f2永远不会大于3。但是,有很多(f1,f2)对。(f1,fk)是UNIQUE。
(f1,f2)
(f1,fk)
UNIQUE
现在,假设我们正在将100和200映射到A,将300和400映射到B,将500映射到C- 这个映射是给定的。我们想(f1_new,fk_mapped)留下来UNIQUE。到目前为止,这大致可以通过以下方式解决
(f1_new,fk_mapped)
INSERT INTO mapped (f1_new,f2_new,fk_new) SELECT f1, MIN(f2), CASE fk WHEN 100 THEN A WHEN 200 THEN A END AS fk FROM origin GROUP BY f1, fk
现在,问题在于我们需要在映射表中保留f2值0、1、2,因此这是期望的结果:
f1_new|f2_new|fk_mapped 1 | 0 |A 1 | 1 |B 2 | 0 |B 2 | 1 |C
我真的很想将其保留在MySQL中。
我认为应该这样做:
INSERT INTO mapped (f1_new, f2_new, fk_new) SELECT f1_new, f2_new, fk_new from ( SELECT f1_new, @f2 := if(f1_new = @prev_f1, @f2+1, 0) f2_new, fk_new, @prev_f1 := f1_new FROM (select f1 AS f1_new, CASE WHEN fk IN (100, 200) THEN 'A' WHEN fk in (300, 400) THEN 'B' WHEN fk = 500 THEN 'C' END AS fk_new FROM origin GROUP BY f1_new, fk_new ORDER BY f1_new, fk_new) new, (SELECT @f2 := NULL, @prev_f1 := NULL) vars ) x
小提琴