初学者在这里。 我正在使用MySQL 5.5.47
我有一个如下的“颜色”表(编辑:请注意,这些ID不是连续的)
+---+---------+
|id |color |
+---+---------+
| 1 | red |
| 4 | yellow |
| 6 | blue |
+---+---------+
和如下所示的“日志”表:
+---------+----------+
|painting | colorid |
+---------+----------+
| a | 1 |
| b | 4 |
| c | 6 |
| d | 1 |
| e | 4 |
+---------+----------+
我需要一个查询,该查询不仅在我插入下一幅画时自动(按顺序)选择下一个色号,而且要“理解”“ 6”(蓝色)之后的下一个色号再次为“ 1”(红色) (就像它们处于循环中一样)。
在此示例中,它将类似于:
INSERT into log (painting, colorid) values ('f', [given that the colorid of the last painting (e) was 4, insert here the "next" colorid of the table colors - in this case 6] )
然后
INSERT into log (painting, colorid) values ('g', [given that the colorid of the last painting (f) was 6, insert here the "next" colorid of the table colors - and as 6 is the last id, "next" means the first id] )
我当时在玩使用LEAD的想法,但是我认为我的版本行不通吗?另一个想法是使用“ colors”表创建一个临时表,该表重复了一种更传统的用法,例如“ where id>(last id)限制为1”