doushenmao9036 2017-02-20 06:23
浏览 86

复制 - 使用MySQL INSERT INTO粘贴行

I have a table that contains many rows, ordered by the field 'seq'. I have selected rows 6-9 and I want to copy and paste them on row 3 for example. For that I'd like to create an SQL query that does the following:

INSERT INTO my_table ( seq, field1, field2.... ) 
SELECT seq, field1,field2..
FROM my_table
WHERE id IN ( 234, 233,232 )

(id field is the auto increment field that identifies my selected rows).

Now - I managed to duplicate the rows into the table. What is missing is to correctly update the 'seq' field in the following manner :

  1. In the pasted location (3) my rows should contain the values 3,4,5.
  2. All the original rows in that location should be incremented by 3 so that the original row (seq=3) should now become (seq=6) and all rows move 3 rows down the table.

Can this be achieved with an SQL query ?

  • 写回答

1条回答 默认 最新

  • douxia9826 2017-02-20 08:56
    关注

    You can create a trigger which check for seq, if a sequence exists, it will update sequence numbers above it and will.

    create table s_sequence 
    (seq number(3),
     name varchar2(2000)
    );
    
    create or replace trigger s_seq_order
      before insert on s_sequence
      for each row
    declare
      seq_exists varchar2(20);
    begin
      begin
        select 1 into seq_exists from s_sequence where seq = :new.seq;
      exception
        when NO_DATA_FOUND then
          null;
      end;
      if seq_exists = '1' then
        update s_sequence set seq = seq + 1 where seq >= :new.seq;
      end if;
    end;
    

    inserting (seq, name) with (1, 'A') , (2, 'B') .. (5, 'E')

    enter image description here

    now insert (2, 'F')

    enter image description here

    But, I am not sure if this is an appropriate way to deal with order. but why put any data in table in order ?

    PS : This code tested in oracle.

    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条