php – 更新列,使其包含行位置

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 更新列,使其包含行位置脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
这是内容表:
ContentID | CategoryID | PosITion | Other1 | Other2
===================================================
1         | 1          | NULL     | abcd   | efgh
2         | 1          | NULL     | abcd   | efgh
3         | 1          | NULL     | abcd   | efgh
4         | 2          | NULL     | abcd   | efgh
5         | 2          | NULL     | abcd   | efgh
6         | 2          | NULL     | abcd   | efgh

这些是我将要运行的查询

SELECT ContentID From content WHERE CategoryID = 1 ORDER BY Position
SELECT ContentID From content WHERE CategoryID = 2 ORDER BY Position

现在我想实现向上移动,向下移动,向上移动到底部功能内容.我需要做的就是用数字填充Position列:

ContentID | CategoryID | Position
=================================
1         | 1          | 1
2         | 1          | 2
3         | 1          | 3
4         | 2          | 1
5         | 2          | 2
6         | 2          | 3

是否可以通过MysqL中的单个查询来实现?就像是:

UPDATE content
SET Position = <ROW_NUMBER>
WHERE CategoryID = 1
ORDER BY Position

UPDATE content
SET Position = <ROW_NUMBER>
WHERE CategoryID = 2
ORDER BY Position
应该工作
update 
content,(
  select 
  @row_number:=ifnull(@row_number,0)+1 as new_position,ContentID 
  from content
  where CategoryID=1
  order by position
) as table_position
set position=table_position.new_position
where table_position.ContentID=content.ContentID;

但是我首先应用这个来取消设置用户定义的变量

set @row_number:=0;

由Mchl添加

你可以在这样的一个声明中做到一点

update 
content,ContentID 
  from content
  where CategoryID=1
  order by position
) as table_position,(
  select @row_number:=0
) as rowNumberInit
set position=table_position.new_position
where table_position.ContentID=content.ContentID;

脚本宝典总结

以上是脚本宝典为你收集整理的php – 更新列,使其包含行位置全部内容,希望文章能够帮你解决php – 更新列,使其包含行位置所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。