只知道方向更新mysql数字字段

时间:2012-05-11 09:06:45

标签: mysql

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

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

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

和第二个(BIGGEST)问题: 例如,我想根据优先级移动第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调用的,我不希望在服务器端执行很多查询。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:-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

我已添加验证,以便它不会尝试更改最高和最低优先级。

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