MySQL-为每个“组”插入增量号

问题描述

| 在下面设置此结果;我试图将红色数字插入post_position-从1开始,与每个ѭ0一样多。 可以使用PHPMyAdmin中的简单查询来完成此操作,还是需要使用PHP? (如果我需要PHP,可以帮您简要介绍一下吗?)     

解决方法

兄弟,我认为这是设计最糟糕的桌子:(添加
id
对于每个值; 后使PHP的:
$result = mysql_query(\"SELECT * FROM <table> ORDER BY topic_id,id\");
$count = 1;
while($r = mysql_fetch_assc($result){
     if(!isset($topic_id) || $topic_id != $r[\'topic_id]){
         $topic_id = $r[\'topic_id];
         $count = 1;
     }
     mysql_query(\"UPDATE <table> SET post_position = {$count} WHERE `id` = {$r[\'id\'}\");
     $count++;
} 
    ,您可以在SQL层使用一些服务器端变量和查询本身中的一堆丑陋逻辑来做到这一点。但是用PHP做到这一点要容易得多。
select @last_group := null; @row_num := 0;

select if(@last_group <> grouped_field_in_your_table,@row_num := @row_num + 1,@row_num := 1),other,fields,here
   @last_group := group_field_in_your_table
from ....
丑陋,但可以完成工作。