我需要在新插入的行中使用位置列的INSERT
值加一个来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
答案 0 :(得分:0)
如果您想在插入中使用子查询,则不必使用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;
答案 1 :(得分:-1)
尝试以下查询:
$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()->query($sql);