当前位置: 代码迷 >> Sql Server >> SQLite没有rownum怎么处理
  详细解决方案

SQLite没有rownum怎么处理

热度:72   发布时间:2016-04-24 09:15:44.0
SQLite没有rownum怎么办?
本人用到SQLite数据库,现在有这么个需求:
 一个Image表,有3列:imageId(主键),indexInBatch(int类型),linkBatchId
示例数据可以如下:
imageId    indexInBatch    linkBatchId
 1            1                1
 2            2                1
 3            3                1
 4            1                2
 5            2                2
 6            3                2
 7            4                2
 8            1                3
 9            2                3

当我删除indexInBatch=2 and linkBatchId=2的那条数据时,我要把linkBatchId=2的那些数据的indexInBatch重新排列,并且重1开始,并且我删除的数据,可以任意选,但是每次删除的数据必须是同一个linkBatchId里面的数据,删除后要对indexInBatch从1开始重新排列,如果在sqlserver里面还好办,有rownum,直接把indexInBatch=rownum where linkBatchId=指定指就行了,但是sqlite里面没有这个rownum,所以我只能一条一条去更新,这样非常耗时,大侠们有什么高招么?望赐教 
------解决思路----------------------
建议在存储过程里去处理,借助临时表、自增列等
------解决思路----------------------
--没什么好办法了
CREATE TABLE #temp
(
imageId  INT,
indexInBatch   INT,
linkBatchId INT
)
INSERT #temp
SELECT 4, 1, 2 UNION ALL
SELECT 6, 3, 2

;WITH cte AS
(
select 
indexInBatch,
(select count(1) from #temp b  where b.linkBatchId = a.linkBatchId and b.imageId <= a.imageId) as cnt
from #temp a
WHERE linkBatchId = 2
)
UPDATE cte
SET indexInBatch = cnt

/*
imageId indexInBatch linkBatchId
4 1 2
6 2 2
*/
  相关解决方案