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

前端之家收集整理的这篇文章主要介绍了php – 更新列,使其包含行位置前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这是内容表:
  1. ContentID | CategoryID | Position | Other1 | Other2
  2. ===================================================
  3. 1 | 1 | NULL | abcd | efgh
  4. 2 | 1 | NULL | abcd | efgh
  5. 3 | 1 | NULL | abcd | efgh
  6. 4 | 2 | NULL | abcd | efgh
  7. 5 | 2 | NULL | abcd | efgh
  8. 6 | 2 | NULL | abcd | efgh

这些是我将要运行的查询

  1. SELECT ContentID FROM content WHERE CategoryID = 1 ORDER BY Position
  2. SELECT ContentID FROM content WHERE CategoryID = 2 ORDER BY Position

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

  1. ContentID | CategoryID | Position
  2. =================================
  3. 1 | 1 | 1
  4. 2 | 1 | 2
  5. 3 | 1 | 3
  6. 4 | 2 | 1
  7. 5 | 2 | 2
  8. 6 | 2 | 3

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

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

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

  1. set @row_number:=0;

由Mchl添加

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

  1. update
  2. content,ContentID
  3. from content
  4. where CategoryID=1
  5. order by position
  6. ) as table_position,(
  7. select @row_number:=0
  8. ) as rowNumberInit
  9. set position=table_position.new_position
  10. where table_position.ContentID=content.ContentID;

猜你在找的PHP相关文章