我有一张表需要复制行。该表是有一个主要的自动递增键以及用于将行组合在一起的列。是否有一种方法可以复制组ID设置为从最后一个值增加的一系列行?
这是基本示例原始表数据
pri | grp
----------
1 | 1
2 | 9
3 | 2
4 | 1
5 | 2
6 | 9
7 | 2
- copied -
8 | 10
9 | 12
10 | 11
11 | 10
12 | 11
13 | 12
14 | 11
我的目标是复制第1-7行并得到如下结果:
SET @new = (SELECT MAX(grp)+1 FROM tbl), @prev = (SELECT MIN(grp) FROM tbl);
INSERT INTO tbl (grp) (
SELECT IF(grp=@prev,
-- set @prev, use @new
, CASE
WHEN (@prev:=grp) IS NULL THEN NULL
ELSE @new
END
-- set @prev, update and use @new
, CASE
WHEN (@prev:=grp) IS NULL THEN NULL
ELSE @new:=@new+1
END)
FROM tbl
ORDER BY grp
)
请注意,复制行的grp在原始Max grp之后开始,然后为每个新grp递增1。
pri | grp
----------
1 | 1
2 | 9
3 | 2
4 | 1
5 | 2
6 | 9
7 | 2
- copied -
8 | 10
9 | 14
10 | 11
11 | 10
12 | 12
13 | 15
14 | 13
这给了我以下结果,看起来@prev变量没有正确更新。
while((fscanf(inputFile1, "%d", &temp1) == 1) && (fscanf(inputFile2, "%d", &temp2) == 1))
{
printf("temp1: %d\n", temp1);
printf("temp2: %d\n", temp2);
if (temp1 > temp2)
{
fprintf(outputFile, "%d\n", temp2);
fprintf(outputFile, "%d\n", temp1);
}
else if (temp1 < temp2)
{
fprintf(outputFile, "%d\n", temp1);
fprintf(outputFile, "%d\n", temp2);
}
else if (temp1 == temp2)
{
fprintf(outputFile, "%d\n", temp1);
fprintf(outputFile, "%d\n", temp2);
}
}
File 1 File 2
5 1
10 43
30 55
50 98
345 500
Output
1
5
10
43
30
55
50
98
345
500
答案 0 :(得分:0)
我认为您需要在子查询中分配新的grp,然后按顺序排序
DROP TABLE IF EXISTS Tbl;
CREATE TABLE Tbl (PRI INT AUTO_INCREMENT PRIMARY KEY, GRP INT);
INSERT INTO Tbl (pri,grp) VALUES
(1 , 1),
(2 , 9),
(3 , 2),
(4 , 1),
(5 , 2),
(6 , 9),
(7 , 2);
INSERT INTO Tbl (grp)
select s.n
from
(
SELECT t.pri tpri,t.grp tgrp
,if(t.grp <> @prev,@new:=@new+1,@new) n
,@prev:=t.grp p
FROM tbl t,(SELECT @new:= (select max(grp) from tbl),@prev:=0) n
order by t.grp
) s
order by s.tpri
;
MariaDB [sandbox]> select * from tbl;
+-----+------+
| PRI | GRP |
+-----+------+
| 1 | 1 |
| 2 | 9 |
| 3 | 2 |
| 4 | 1 |
| 5 | 2 |
| 6 | 9 |
| 7 | 2 |
| 8 | 10 |
| 9 | 12 |
| 10 | 11 |
| 11 | 10 |
| 12 | 11 |
| 13 | 12 |
| 14 | 11 |
+-----+------+
14 rows in set (0.00 sec)