php - MYSQL IF 语句按类别重新排序

标签 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

I have tried this syntax:

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

Solution code:

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

最佳答案

尝试

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

顺便说一句,order 是 MySQL 中的保留字。你必须用反引号转义它

关于php - MYSQL IF 语句按类别重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11580234/

相关文章:

PHP echo 不打印

php - 如何从 phing 临时任务返回值?

php - 使用户无法访问 'sitemap.xml',但机器人可以访问

c# - 使用 MySQL 5、简单成员身份提供程序、ASP.NET MVC4 和 Entity Framework 5

arrays - postgresql 插入语句中的 perl 数组

javascript if语句不起作用

php - Mysql count(*) 让我失望

php - 如何使用事件记录从表中选择 *,其中 col1+col2=b

php - 导入 CSV 数据时跳过重复值

jquery end 阻止菜单上最后一个链接上的 default()