php - 在数据库中插入行并更新其下面的行

标签 php mysql sql database

您好,我目前正在使用一个系统,该系统可以比较两个人输入的 2 个页面并进行编辑,但首先我将每行数据插入到数据库中,因此输出如下所示

一个

两个

四个

这是数据库

id   pagenum  linenum   data   bookname
1       1        1      one    twilight
2       1        2      two    twilight
3       1        3      three  twilight
4       1        4      four   twilight
5       1        5      five   twilight
6       1        6      six    twilight

但我想在 id 号 2 和 3 之间插入 2 行,并更新其上及其下方的行号 所以我要查询上面的行号,我将把它放在哪里,所以查询 linenumb where id= 2+1 所以 3 将是我要添加的 2 行的起始行号,所以它将是第 3 行和第 4 行,但困境就在那里将是 2 pagenum=1 linenum=3 和 pagenum=1 和 linenum=4 有人可以帮助我解决如何修复它的结构

所以毕竟数据库应该是这样的

id   pagenum  linenum   data   bookname
1       1        1      one    twilight
2       1        2      two    twilight
7       1        3    newline  twilight //this is the 1st line i added
8       1        4    newline  twilight //this is the 2nd line i added
3       1        5      three  twilight
4       1        6      four   twilight
5       1        7      five   twilight
6       1        8      six    twilight

我有一个困境,应该在添加的行的行号中放入什么,我应该像这样对它们进行排队

就像插入...2和3 计数,起始值应为 3+1,计数将是更新和递增的次数,然后更新底部页面 或将行号留空并 计算整个页面并更新它们

或者我应该将所有数据向下移动 2 行?像这样

id   pagenum  linenum   data   bookname
1       1        1      one    twilight
2       1        2      two    twilight
3       1        3    newline  twilight 
4       1        4    newline  twilight 
5       1        5      three  twilight
6       1        6      four   twilight
7       1        7      five   twilight//i moved this 2 rows down and so this is the inserted value
6       1        8      six    twilight//i moved this 2 rows down and so this is the inserted value

这是最简单、最有效的方法

最佳答案

确定您将从 (3) 开始插入的行号。

然后获取您要插入的行数 (2)。

<?php
    $start = 3;
    $rows = 2;
?>

然后运行此查询:

UPDATE table SET linenum = linenum + $rows WHERE linenum >= $start

这将使您的表格看起来像:

id   pagenum  linenum   data   bookname
1       1        1      one    twilight
2       1        2      two    twilight
3       1        5      three  twilight
4       1        6      four   twilight
5       1        7      five   twilight
6       1        8      six    twilight

现在您的新行有一个间隙,因此请插入它们。

关于php - 在数据库中插入行并更新其下面的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19430530/

相关文章:

php - 在 Symfony 4.1 中使用 grpc,找不到 “Class ' Grpc\ChannelCredentials'。”

php - 文本区域上的 nl2br 和 htmlentities

javascript - 'heavy' 是如何在服务器上每隔几秒运行一次mysql命令

mysql - 如何: Export a recordset as a semicolon separated csv file in MySQL workbench?

mysql - SQL 多个 INNER JOIN 和 GROUP BY

在 MySQL 查询的 LIMIT 子句中使用占位符时出现 PHP PDO 错误

mysql - 获取 : java. sql.SQLException:未知系统变量 'language' spring boot

SQL只选择最高日期

java - Ebean ManyToOne 可为空联接

php - 如何知道点击了哪个按钮?