如何使用索引更新重复的行(Mysql)

时间:2014-03-18 01:25:48

标签: mysql sql procedure

我有一张桌子,名为city。

city_name
---------------
New York
Beijing
New York
New York
Dubai
Beijing
---------------

更新后,我希望它是:

city_name,   index
---------------
New York,    0
Beijing,     0
New York,    1
New York,    2
Dubai,       0
Beijing,     1
---------------

模式是这样的:第一个纽约的索引是0,第二个纽约的索引是1,第三个索引是2.这个表中有数百万行。 / p>

进行此次更新的简单方法是什么?

我正在考虑分两步解决这个问题。

第一步:

@cities = Select distinct city_name from city;

第二步:

foreach @cities as @city
   update city set index = row_num where city_name = @city.cityname

似乎row_num在mysql中不可用。

2 个答案:

答案 0 :(得分:2)

试试这个:

update city cross join
       (select @city := '', @prevcity := '', @i := 0) const
    set `index` = (case when (@prevcity := @city) is null then null
                        when (@city := city) is null then null
                        else @i := if(@prevcity = city, @i + 1, 1) is null then null
                   end)
    order by city; 

如果您熟悉在select语句中使用变量进行枚举,那么这是类似的。复杂性是确保update的评估顺序。这是通过使用case语句来处理的,该语句按顺序计算每个子句,直到有一个为真。前两个保证是假的(因为值不应该是NULL)。

编辑:

如果您有唯一的ID,那么解决方案会更容易一些。我希望你能做到这一点:

update city c
    set `index` = (select count(*) from city c2 where c2.city = c.city and c2.id <= c.id);

但相反,您可以使用更多连接来实现:

update city c join
       (select id, (select count(*) from city c2 where c2.city = c1.city and c2.id <= c1.id) as newind
        from city c1
       ) ci
       on c.id = ci.id
    set c.`index` = ci.newind;

答案 1 :(得分:1)

使用session()进行存储和比较的方法:

  session_start();

  $number=0;
  $result=mysqli_query($yourconnection,"SELECT * FROM city ORDER BY city_name");

  while($row=mysqli_fetch_array($result)){

  if(empty($_SESSION["storage"])){ 
  /* THIS CONDITION ONLY GOES THROUGH THE VERY FIRST ARRAY FETCH */

  $_SESSION["storage"]=$row['city_name'];

  mysqli_query($yourconnection, "UPDATE city SET index='$number' WHERE city_name='$cityname'"); /* STORE TO THE FIRST CITY'S INDEX 0 */

  }

  else if($_SESSION["storage"]==$row['city_name']){ 
  /* IF SESSION IS THE SAME COUNTRY AS THE CURRENT ROW COUNTRY */

  $_SESSION["storage"]=$row['city_name'];

  $number=$number+1; /* INCREMENT NUMBER FOR THE SAME COUNTRY */

  mysqli_query($yourconnection, "UPDATE city SET index='$number' WHERE city_name='".$row['city_name']."'");


  }

  else {

  /* THIS IS FOR THE NEXT NEW COUNTRY */

  $number=0; /* START AGAIN THE COUNT TO 0 IF NEW COUNTRY */

  $_SESSION["storage"]=$row['city_name'];

  mysqli_query($yourconnection, "UPDATE city SET index='$number' WHERE city_name='".$row['city_name']."'");

  }

  } /* END OF WHILE LOOP */

我以前做过这个,但输出不同,但逻辑相同。我使用另一个表进行存储和比较。但是我上面的代码,我用的是session。