简体   繁体   English

带有子查询的MySQL条件UPDATE

[英]MySQL conditional UPDATE with subquery

What I am trying to achieve is the following: update an existing table where each row has field "order-id" (incremented sequentially from 0). 我想要实现的是:更新现有的表,其中每行具有字段“order-id”(从0开始按顺序递增)。 Now, if a row is deleted I want to ensure consistency of "order-id", ie starting from 0, incremented by 1. Example: Rows with order-id 0,1,2,3 - then row with order-id "2" gets deleted. 现在,如果删除了一行,我想确保“order-id”的一致性,即从0开始,递增1.示例:订单ID为0,1,2,3的行 - 然后是带有order-id的行2“被删除。 I am looking for the SQL-statement that makes sure the order is not "0,1,3", but "0,1,2" ordered by the existing order-id (hence the ORDER BY in the subequery) 我正在寻找确保订单不是“0,1,3”的SQL语句,而是现有order-id排序的“0,1,2”(因此子查询中的ORDER BY)

Here's what I have so far - works, but doesn't take ORDER BY into account for some reason 这是我到目前为止所做的工作,但由于某些原因不考虑ORDER BY

UPDATE walklist_walks AS w, 
   (SELECT walk_id, order_id,@n := -1 
   FROM walklist_walks 
   WHERE walklist=8 
   ORDER BY order_id ASC) m
SET w.order_id = @n := @n + 1
WHERE w.walklist = 8 
AND w.walk_id=m.walk_id

Here's some sample data: 这是一些示例数据:

   ROW 1: "walk_id 1059, order_id 0, walklist 8", 
   ROW 2: "walk_id 821, order_id 399, walklist 8", 
   ROW 3: "walk_id 91, order_id 45, walklist 8" 

After running the query this should look like 运行查询后,这应该是这样的

   ROW 1: "walk_id 1059, order_id 0, walklist 8", 
   ROW 2: "walk_id 91, order_id 1, walklist 8", 
   ROW 3: "walk_id 821, order_id 2, walklist 8"

What if you convert it to a update-join construct like 如果将其转换为update-join构造,该怎么办?

UPDATE walklist_walks AS w JOIN 
   (SELECT walk_id, order_id,@n := -1 
   FROM walklist_walks 
   WHERE walklist=8 
   ORDER BY order_id ASC) m ON w.walk_id=m.walk_id
SET w.order_id = @n := @n + 1
WHERE w.walklist = 8;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM