数据库表
id serial account speeddialsort dest
107 155 501 1 020341542
115 155 501 2 004407152222
116 155 501 3 00951242454
117 155 501 4 0794245544
118 266 700 1 004465652212
119 266 700 2 0044845482
向用户提供的数据
这是帐户的501快速拨号插槽列表。 我可以从表单中发送speeddialsort和dest,然后我可以用什么sql方法来管理用户编辑快速拨号顺序。
订单上下移动
speeddialsort dest
#1 020341542
#2 004407152222
#3 00951242454
#4 0794245544
例如,用户选择快速拨号#3向上移动。需要交换#2和#3的speeddialort
答案 0 :(得分:0)
我认为speeddialsort是UNIQUE而dest不是吗?
Asume $ int_short提供sort_id和$ int_previous_sort为值之前是:
INSERT INTO table (speeddialsort, dest)
SELECT speeddialsort, dest
FROM (SELECT {$int_sort} AS speeddialsort, dest
FROM table
WHERE speeddialsort = {$int_previous_sort}
UNION ALL
SELECT {$int_previous_sort}, dest
FROM table
WHERE speeddialsort = {$int_sort})
ON DUPLICATE KEY UPDATE dest = VALUES(dest)
如果两者都是独一无二的,那么简单地删除和读取它们会更容易。那,或者:
INSERT INTO table (speeddialsort, dest)
SELECT speeddialsort, dest
FROM (SELECT {$int_sort} AS speeddialsort, NULL AS dest
UNION ALL
SELECT {$int_previous_sort}, NULL
UNION ALL
SELECT {$int_sort}, dest
FROM table
WHERE speeddialsort = {$int_previous_sort}
UNION ALL
SELECT {$int_previous_sort}, dest
FROM table
WHERE speeddialsort = {$int_sort})
ON DUPLICATE KEY UPDATE dest = VALUES(dest)
也应该工作。
答案 1 :(得分:0)
上移:
UPDATE my_table AS t1 SET t1.dest =
IFNULL( ( SELECT t2.dest FROM my_table AS t2
WHERE t2.speeddialsort IN( {$i}, {$i-1} ) AND
t2.account = $account AND t2.dest <> t1.dest ), t1.dest )
WHERE t1.speeddialsort IN( {$i}, {$i-1} ) AND t1.account = {$account}
到向下移动只需将$i-1
替换为$i+1
($ i是您要移动的speeddialort,$ account是帐户ID)
答案 2 :(得分:0)
我创建了一个表,并使用连续序列生成行序列 mysql user defined variable.
ID serial
101 1
103 2
104 3
110 4
在此处将序列4移动到2
SET @a = 2;
UPDATE tableName SET serial = @a:=@a + 1 WHERE serial >= 2 AND serial < 4
ORDER BY serial DESC;
UPDATE tableName SET serial = 2 WHERE ID = 1;
此查询将为小于4且大于2的所有序列值添加1,然后使用值为2的序列4更新行。
将第2项移至4
SET @b = 4;
UPDATE tableName SET ord = @b:=@b - 1 WHERE serial > 2 AND serial < (4 + 1)
ORDER BY serial DESC;
UPDATE tableName SET serial = 4 WHERE ID = 1 ;
我不是在谈论Auto Increment。在我的情况下,我需要按用户要求订购这些值。所以我不能使用自动增量。