2017-06-19 115 views
0

我按表格形式在sqlite上按字母顺序输入单词,它已被编号......假设我想在sylite经理的两行之间添加一行,也许编号为2 “aa”和3号是“ac”,如果我想在aa和ac之间添加“ab”,并使ab号码3和ac号码4,我该如何轻松地做到这一点?如何在sqlite管理器上的两行之间插入另一行

回答

1

DBFiddle Demo of Update Statement

由于sqlite的不支持Windows的分析功能,这将是有点棘手,实现这一目标。您也可以使用类似的逻辑创建一个before insert触发器。

假设:

  1. 号码与任何整数开始,像在这种情况下2并将于1递增。所以现有数据中没有丢失序列。

  2. 字母数字排序是适用其中aa < aaa < ab < ac。这由RDBMS根据字符串中每个字符的ascii值完成,从第一个字符开始。

  3. 您正在插入值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_iddifference实际id。与上述情况一样,如果我们生成的号码从1n,您的ID以2开头。所以这两个diff1,我会用它来添加所有生成的ID,得到new_id。可能有一个更容易的方法,但这是我现在能想到的。

现在我们在更新声明中使用此查询来更新idnew_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 
    ); 
相关问题