Mysql:按顺序将值插入间隙

时间:2017-10-05 06:52:53

标签: php mysql

所以我的问题是:检查1 - 14中缺少哪些行,然后将INSERT我的新值检查到打开行中的最佳方法是什么。

我知道没有必要填补你的数据库中的空白,但我正在做一个PHP课程,我需要实现以下目标:

我的表格primary key设置为id,但不是auto_increment。因此,如果删除了14个值中的一个,则需要将新值放在间隙中。

我已经阅读了一些内容,并在SO上发现了一些问题,但他们只是想检查是否存在差距,我不知何故需要告诉它允许更新值的内容和位置。

我有这个

SELECT MIN(t1.position_id)+1 AS unused
    FROM playerposition AS t1
    WHERE NOT EXISTS (SELECT * FROM playerposition AS t2 WHERE t2.position_id = t1.position_id+1)
    UNION
    -- Special case for missing the first row
    SELECT 1
    FROM DUAL
    WHERE NOT EXISTS (SELECT * FROM playerposition WHERE position_id = 1)
) AS subquery

但这只会返回第一行而我并不真正了解查询。任何帮助,建议或指导将不胜感激。

更新

我对查询进行了更改,现在我得到了空值。我的新查询看起来像这样

SELECT a AS id, b AS next_id, (b - a) -1 AS missing_inbetween
FROM
  (
    SELECT a1.position_id AS a, MIN(a2.position_id) AS b
    FROM playerposition  AS a1
      LEFT JOIN playerposition AS a2 ON a2.position_id > a1.position_id
    WHERE a1.position_id <= 14
    GROUP BY a1.position_id
  ) AS tab

WHERE
  b > a + 1

我仍需要INSERT部分的帮助

1 个答案:

答案 0 :(得分:0)

以下代码帮助我实现了我想要的结果。我相信可以进行改进以使代码更好

if (mysqli_num_rows($resultCheckPos) == 14) {
        echo "You can only have 14 positions in total";
    } else {
        $testQ = "SELECT min(unused) AS unused
FROM (
    SELECT MIN(t1.position_id)+1 AS unused
    FROM playerposition AS t1
    WHERE NOT EXISTS (SELECT * FROM playerposition AS t2 WHERE t2.position_id = t1.position_id+1)
    UNION
    -- Special case for missing the first row
    SELECT 1
    FROM DUAL
    WHERE NOT EXISTS (SELECT * FROM playerposition WHERE position_id = 1)
) AS subquery";

        $resultTest = $conn->query($testQ);
        $rowTest = mysqli_fetch_assoc($resultTest);
        $row = $rowTest['unused'];

        $insertTest = "INSERT INTO playerposition (position_id, position_descr) VALUES ('$row','$posDesc')";
        $resultInsertTest = $conn->query($insertTest);
        header("Refresh:0");
    }