我有一张像
这样的表格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
。
现在,假设我们将100和200映射到A,300和400映射到B,500到C - 这个映射是给定的。我们希望(f1_new,fk_mapped)
留下UNIQUE
。到目前为止,这大致由
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中。
答案 0 :(得分:3)
我认为应该这样做:
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