我有两个包含如下列的表:
表1:+------------+-----------+------+--------+---------+
| LocalDate | Available | Away | Online | Offline |
+------------+-----------+------+--------+---------+
| 2016-08-11 | 600 | 1039 | 163 | 600 |
+------------+-----------+------+--------+---------+
TABLE_2:
key | value
1 | apple
2 | banana
3 | carrot
使用存储过程,我想使用INSERT ... SELECT将Table_1中的行插入Table_2,这样每次执行查询时,
sub_index | value
都从1开始。
例如,在我第一次运行查询sub_index
Table_2应如下所示:
INSERT INTO TABLE_2 (value) SELECT value FROM TABLE_1 WHERE key=2
然后如果我运行另一个查询
sub_index | value
1 | banana
Table_2现在看起来像这样:
INSERT INTO TABLE_2 (value) SELECT value FROM TABLE_1 WHERE key < 4
如果我运行进一步的查询
sub_index | value
1 | banana
1 | apple
2 | banana
3 | carrot
Table_2现在看起来像这样:
INSERT INTO TABLE_2 (value) SELECT value FROM TABLE_1 WHERE key <= 2
换句话说,每次运行查询时,我希望
sub_index | value
1 | banana
1 | apple
2 | banana
3 | carrot
1 | apple
2 | banana
字段从1开始,并为查询插入的每个记录递增。
如何仅使用SQL为sub_index
实现此行为? (即没有用PHP编程。)
感激地收到任何建议!
答案 0 :(得分:2)
set @row_nb=0;
INSERT INTO Table_2 (`sub_index`,`value`) select (@row_nb := @row_nb +1) as `key`,`value` from Table_1 WHERE `key`< 4