从IDS列表更新订单列

时间:2019-01-11 13:39:02

标签: mysql

我在MySQL Server 5.7.24上有N个ID的列表(例如:803、518、361)

当前值为

SeekOrigin.End

我想从ID列表中更新+-----+-------+ | id | order | +-----+-------+ | 361 | 1 | | 518 | 2 | | 803 | 3 | +-----+-------+ 列,以从ID位置获取订单。

此查询为每个order返回正确的rownum

id

但是在更新时,未设置此位置:

SELECT `id`, (@rownumber := @rownumber + 1) `rownum`
FROM `comments`
CROSS JOIN (SELECT @rownumber := 0) `cross`
WHERE `id` IN (803, 518, 361)
ORDER BY FIELD (`id`, 803, 518, 361) ASC;

+-----+--------+
| id  | rownum |
+-----+--------+
| 803 |      1 |
| 518 |      2 |
| 361 |      3 |
+-----+--------+

订单值未更新:

UPDATE `comments` `target`
JOIN (
    SELECT `id`, (@rownumber := @rownumber + 1) `rownum`
    FROM `comments`
    CROSS JOIN (SELECT @rownumber := 0) `cross`
    WHERE `id` IN (803, 518, 361)
    ORDER BY FIELD (`id`, 803, 518, 361) ASC
) `source` ON `target`.`id` = `source`.`id`
SET `target`.`order` = `source`.`rownum`;

Query OK, 0 rows affected (0.00 sec)
Rows matched: 3  Changed: 0  Warnings: 0

查询哪里出问题了?

谢谢!

更新1:

也不能正常工作

SELECT `id`, `order` FROM `comments`
WHERE `id` IN (361, 518, 803)
ORDER BY `order` ASC;

+-----+-------+
| id  | order |
+-----+-------+
| 361 |     1 |
| 518 |     2 |
| 803 |     3 |
+-----+-------+
3 rows in set (0.01 sec)

3 个答案:

答案 0 :(得分:1)

以下查询应该可以解决问题:

random

请参见this db fiddle

答案 1 :(得分:1)

由于id是主键,因此您只需执行以下操作即可:

UPDATE `comments`
       SET `order` = field(`id`,
                           803,
                           518,
                           316)
       WHERE `id` IN (803,
                      518,
                      361);

field()已经产生了123

答案 2 :(得分:0)

当我在PHP上处理查询时,感谢@​​GMB具有运行两个不同语句的想法:

$db->exec('SET @rownumber = 0;');

$db->exec('
    UPDATE `comments`
    SET `order` = @rownumber := @rownumber + 1
    WHERE `id` IN (803, 518, 361)
    ORDER BY FIELD (`id`, 803, 518, 361) ASC;
');