MYSQL IF语句按类别重新排序

时间:2012-07-20 13:21:55

标签: php mysql if-statement sql-update sql-order-by

我一直在尝试根据菜单结构的类别和订单ID重新排序数据库中的表。

这就是我大致作为表格结构

menuid menuname      order categoryid
--------------------------------------
1      firstitem       1      1
2      seconditem      2      1
3      thirditem       1      2
4      fourthitem      2      2

我尝试过这种语法:

UPDATE yourtable SET id=IF(id=2, 3, 2) where id in(2,3)
像这样:

UPDATE menu
SET order = IF(order = `3`, `2`, `3`)
WHERE order = `3`

我收到此错误:

You have an error in your SQL syntax; check the manual that corresponds to your
 MySQL server version for the right syntax to use near 'order = IF(order = `3`, `2`, `3`)
 WHERE order = `3`' at line 2

解决方案代码:

UPDATE menu
SET `order` = case when `order` = 3 then 2 else 3 end
WHERE `order` = 3 AND section = 2 OR `order` = 2 AND section = 2

2 个答案:

答案 0 :(得分:1)

UPDATE menu
SET `order` = case when `order` = 3 
                   then 2 
                   else `order` 
              end

顺便说一句order是MySQL中的保留字。你必须用反引号来逃避它

答案 1 :(得分:1)

为什么不使用CASE表达式。你的WHERE没有意义

UPDATE menu 
SET order = case when order = `3` then `2` else `3` end