[英]MySQL: Insert new record using MAX value of a column in the same table
I need to INSERT
a new record, using the MAX
value of the position column plus one, in the newly inserted row. 我需要在新插入的行中使用位置列的MAX
值加1来INSERT
一条新记录。 So if the MAX
value is 14, the next inserted row's position column value should be 15. 因此,如果MAX
值为14,则下一个插入行的位置列值应为15。
This is my current code, which is working but it needs 2 separate queries: 这是我当前的代码,正在运行,但是需要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();
I wanted to know if there is some way to achieve the same result with just one query: 我想知道是否有某种方法可以仅通过一个查询来达到相同的结果:
# 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();
That test is throwing an error. 该测试抛出一个错误。 Is it possible to achieve this with a similar approach? 是否可以通过类似的方法来实现?
I built the schema in sqlfiddle: http://sqlfiddle.com/#!9/228058/1 我在sqlfiddle中构建了架构: http ://sqlfiddle.com/#!9/228058/1
If you want to use a subquery in an Insert you don't have to use VALUES
如果要在插入中使用子查询,则不必使用VALUES
Try this query: 试试这个查询:
INSERT INTO store_item_photo (id_item, position)
SELECT
3 AS id_item,
MAX(position) + 1
FROM store_item_photo
WHERE id_item = 3;
Try this 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()->query($sql);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.