1

我有这样的mysql表:id, [.....], priority

优先级字段用于根据需要对表进行排序。它基于人类的智慧。我有一些价值观:

id, priority
1, 1
2, 7
3, 2
4, 4
5, 6
6, 5
7, 3

第二个(最大)问题:例如,我想根据优先级向上向下移动第 4 个元素。

第 4 个元素向上(左)和向下(右)移动

    1, 1         1,1
    2, 7         2,7
    3, 2         3,2
    4, 3         4,5
    5, 6         5,6
    6, 5         6,4
    7, 4         7,3

我想用单个 mysql 查询来做,因为它是通过 ajax 调用的,我不希望在服务器端执行很多查询。

4

3 回答 3

0

不改变优先级只是交换优先级吗?这里有一个很好的解决方案:Swap values in 2 rows SQL。这将交换记录 1 和 4 的优先级

UPDATE yourtable AS t1
JOIN yourtable AS t2 ON 
       (t1.id = 1 AND t2.id = 4)
    OR (t1.id = 4 AND t2.id = 1)
SET
    t1.priority = t2.priority,
    t2.priority = t1.priority

实际上,如果您的优先级是唯一的,您可以不使用 id 进行交换,而只需使用优先级。这将交换优先级 4 和 5:

UPDATE yourtable AS t1
JOIN yourtable AS t2 ON 
       (t1.priority = 4 AND t2.priority = 5)
    OR (t1.priority = 5 AND t2.priority = 4)
SET
    t1.priority = t2.priority,
    t2.priority = t1.priority
于 2012-05-11T09:33:29.353 回答
0

如果您需要将 4 向下移动:

UPDATE your_table AS t1 JOIN your_table AS t2 ON (t1.id = 4 AND t2.priority = t1.priority + 1) SET t1.priority = t2.priority, t2.priority = t1.priority

或者,如果您需要将 2 向上移动:

UPDATE your_table AS t1 JOIN your_table AS t2 ON (t1.id = 2 AND t2.priority = t1.priority - 1) SET t1.priority = t2.priority, t2.priority = t1.priority
于 2012-05-11T09:38:02.213 回答
-1
$int_prio = (1 - ((int)($_POST['move_up'] == 'TRUE') * 2));
$int_id = (int)$_POST['id'];

mysql_query("
INSERT INTO table_name (id, priority)
SELECT h2.id, 
    (h2.priority + ({$int_prio} * (1 - (2 * (h.id != h2.id))))) AS priority
FROM (  SELECT id, priority
        FROM table_name
        WHERE id = {$int_id}
        HAVING priority BETWEEN 2 AND ( SELECT MAX(priority)
                                        FROM priority
                                        GROUP BY '1') - 1) AS h
INNER JOIN priority AS h2
ON h.priority IN (h2.priority, h2.priority + {$int_prio})
ON DUPLICATE KEY UPDATE priority = VALUES(priority)
");

基本上更改 $_POST (最好更安全)和table_name.

我添加了验证,因此它也不会尝试更改最高和最低优先级。

抱歉,如果您发现上述查询令人困惑,但这是一种通过添加验证在单个查询中更新所有内容的方法。

于 2012-05-11T09:29:11.673 回答