[英]Set unique value in column and if its not unique move other one down
I have problem with this. 我对此有疑问。 What I need is to get unique values in column called order
in my event
table. 我需要在event
表中的名为order
列中获得唯一值。 How this thing should behave: for example I have table `event 这件事应该如何表现:例如我有table`event
| id | name | order |
|----|---------|-------|
| 1 | walking | 1 |
| 2 | diving | 2 |
| 3 | skating | 3 |
for example when I try to update skating
order to 1
I will get 例如,当我尝试将skating
顺序更新为1
时,
| id | name | order |
|----|---------|-------|
| 3 | skating | 1 |
| 1 | walking | 2 |
| 2 | diving | 3 |
Have no idea how to do it, tried this but it doesn't work for me: 不知道该怎么做,尝试了一下,但对我不起作用:
Yii::$app->db->createCommand("
SET @rownum :=0;
UPDATE " . self::tableName() . "
LEFT JOIN (
SELECT id, (@rownum := @rownum + 1) AS rowNumber
FROM " . self::tableName() . "
ORDER BY order ASC
) as tmp_table
on tmp_table.id = " . self::tableName() . ".id
SET " . self::tableName() . ".order = tmp_table.rowNumber"
)->execute();
If it's not understandable for you, ask me I will try to explain all the things. 如果您无法理解,请问我,我将尽力解释所有事情。
You don't need to regenerate all the orders using a user variable, since you're just adding 1
to them, except for the element that moves into position 1
. 您不需要使用用户变量来重新生成所有订单,因为您只需向其添加1
,除了移动到位置1
的元素。 So you can do it with IF
or CASE
. 因此,您可以使用IF
或CASE
。
UPDATE yourTable
SET `order` = CASE name
WHEN 'skating' THEN 1
ELSE `order` + 1
END
If you need to be able to move the element to some place other than 1
, then it gets a little more complicated: 如果您需要将元素移动到1
以外的其他位置,则它会变得更加复杂:
UPDATE yourTable
SET `order` = CASE
WHEN name = 'skating' THEN @newpos
WHEN `order` >= @newpos THEN `order` + 1
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.