我按表格形式在sqlite上按字母顺序输入单词,它已被编号......假设我想在sylite经理的两行之间添加一行,也许编号为2 “aa”和3号是“ac”,如果我想在aa和ac之间添加“ab”,并使ab号码3和ac号码4,我该如何轻松地做到这一点?如何在sqlite管理器上的两行之间插入另一行
0
A
回答
1
DBFiddle Demo of Update Statement
由于sqlite的不支持Windows的分析功能,这将是有点棘手,实现这一目标。您也可以使用类似的逻辑创建一个before insert
触发器。
假设:
号码与任何整数开始,像在这种情况下
2
并将于1
递增。所以现有数据中没有丢失序列。字母数字排序是适用其中
aa
<aaa
<ab
<ac
。这由RDBMS根据字符串中每个字符的ascii值完成,从第一个字符开始。您正在插入值
ab
而没有任何id
。在执行下面的更新语句之后,将id
分配给val
。通过使用类似的逻辑,您可以实现与before insert
触发器相同的操作。
第一个查询确定new_id
。
select t.*,
(select count(*) from test t1 where t.val>=t1.val) +
o.diff as new_id
from test t
cross join
(select * from
(select t.*,(select count(*) from test t1 where t.val>=t1.val) as rn ,
id - (select count(*) from test t1 where t.val>=t1.val) as diff
from test t
) where rn=1
) o
输出
+------+-----+--------+
| id | val | new_id |
+------+-----+--------+
| 2 | aa | 2 |
| 3 | ac | 4 |
| null | ab | 3 |
+------+-----+--------+
我使用cross join
因为首先我们要确定的min_id
的difference
实际id
。与上述情况一样,如果我们生成的号码从1
到n
,您的ID以2
开头。所以这两个diff
是1
,我会用它来添加所有生成的ID,得到new_id
。可能有一个更容易的方法,但这是我现在能想到的。
现在我们在更新声明中使用此查询来更新id
与new_id
。
update test
set id = (select tb.new_id from
(select t.*,
(select count(*) from test t1 where t.val>=t1.val) +
o.diff as new_id
from test t
cross join
(select * from
(select t.*,(select count(*) from test t1 where t.val>=t1.val) as rn ,
id - (select count(*) from test t1 where t.val>=t1.val) as diff
from test t
) where rn=1
) o
) tb
where test.val=tb.val
)
where exists
(select * From (select t.*,
(select count(*) from test t1 where t.val>=t1.val) +
o.diff as new_id
from test t
cross join
(select * from
(select t.*,(select count(*) from test t1 where t.val>=t1.val) as rn ,
id - (select count(*) from test t1 where t.val>=t1.val) as diff
from test t
) where rn=1
) o
) tb
where test.val=tb.val
);
相关问题
- 1. 在两行之间插入行
- 2. sql - 插入两行之间?
- 3. 如何在另一个文件之间插入几行文字
- 4. 在表中的两行之间插入一行
- 5. 在插入两行中的一行时捕获两行之间的关系
- 6. 如何在Sql中的两个现有行之间的表中插入一行
- 7. 如何在HSSF(Apache POI)的现有Excel中的两行之间插入一行
- 8. 如何避免动态插入两行之间的新行
- 9. 如何选择在另一行之前插入的行,时间戳?
- 10. 如何在Android sqlite中的现有行之前插入新行?
- 11. 如何在sqlite插入触发器之前进行验证
- 12. 如何在两个条件之间插入换行符条件
- 13. 在SQL中插入两行之间的行
- 14. 插入两个已知行之间的行在Matlab
- 15. 如何在Winform c#ListView中的两行之间插入行分隔符?
- 16. SQLite,删除另一行后插入一行时出错?
- 17. MySQL管理器 - 选择插入空行
- 18. Oracle - 在两次之间每小时插入一行
- 19. 如何在使用Python在SQLite中插入行之后检索插入的id?
- 20. 如何在同一时间插入两个arralist到SQLite?
- 21. 如何在sqlite中插入多行android
- 22. 如何在两个sqlite-memory-database之间进行复制?
- 23. 按组插入行之间的行
- 24. 如何在每个SQLite行中插入一个唯一的ID?
- 25. 如何评论一行并在其下插入另一行?
- 26. 如何在SAS中插入一行相对于另一行
- 27. 插入行表,如果在另一台
- 28. Android如何在另一个线程上执行db插入?
- 29. 如何插入两种颜色之间?
- 30. 在SQLite中读取(从另一个表中)时插入行