gpt4 book ai didi

php - MySQL:使用同一表中列的最大值插入新记录

转载 作者:行者123 更新时间:2023-11-30 23:43:38 24 4
gpt4 key购买 nike

我需要INSERT 一条新记录,在新插入的行中使用position 列的MAX 值加一。因此,如果 MAX 值为 14,则下一个插入行的位置列值应为 15。

这是我当前的代码,可以正常工作,但需要 2 个单独的查询:

# get position order
$sql = 'SELECT MAX(position) FROM store_item_photo WHERE id_item = 3';
$stmt = cnn()->prepare($sql);
$stmt->execute();
$position = $stmt->fetchColumn();
$position++;

# photo: new record
$sql = 'INSERT INTO store_item_photo (id_item, position) VALUES (3, :position)';
$stmt = cnn()->prepare($sql);
$stmt->bindValue(':position', $position, PDO::PARAM_INT);
$stmt->execute();

我想知道是否有某种方法可以通过一个查询获得相同的结果:

# photo: new record (one query)
$sql = 'INSERT INTO store_item_photo (id_item, position) VALUES (3, (SELECT MAX(position) FROM store_item_photo WHERE id_item = 3) + 1)';
$stmt = cnn()->prepare($sql);
$stmt->execute();

该测试抛出错误。是否可以通过类似的方法实现这一目标?

我在 sqlfiddle 中构建了模式:http://sqlfiddle.com/#!9/228058/1

最佳答案

如果您想在插入中使用子查询,则不必使用 VALUES

试试这个查询:

INSERT INTO store_item_photo (id_item, position)
SELECT
3 AS id_item,
MAX(position) + 1
FROM store_item_photo
WHERE id_item = 3;

关于php - MySQL:使用同一表中列的最大值插入新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55178152/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com