开发者

MySQL - How to update atable based on an internal ordering of the table

If I make a selection from my MySQL table like:

SELECT * FROM mytable ORDER BY country_id, category

I get the following table:

+------------+----------+-------+
| country_id | category | order |
+------------+----------+-------+
|          1 |        A |     0 |
|          1 |        B |     0 |
|          1 |        F |     0 |
|          3 |        A |     0 |
|          3 |        C |     0 |
|          5 |        B |     0 |
|          5 |        L |     0 |
|          5 |        P |     0 |
+------------+----------+-------+

What I would like to do is update the order column so that the value of that column is th开发者_StackOverflow中文版e order of that row for it's country_id. In other words the final table should look like this:

+------------+----------+-------+
| country_id | category | order |
+------------+----------+-------+
|          1 |        A |     1 |
|          1 |        B |     2 |
|          1 |        F |     3 |
|          3 |        A |     1 |
|          3 |        C |     2 |
|          5 |        B |     1 |
|          5 |        L |     2 |
|          5 |        P |     3 |
+------------+----------+-------+

If I use the original query given at the top in a subquery, that would give me the correct order but I can't figure out how to iterate through the table and suspect I thinking about it wrongly.

How can I get this result?

Many thanks


Try to use this query -

UPDATE mytable t1
  JOIN (
    SELECT t1.country_id, t1.category, COUNT(*) `order`
    FROM mytable t1
    LEFT JOIN mytable t2
      ON t2.country_id = t1.country_id AND t2.category <= t1.category
    GROUP BY
      t1.country_id, t1.category
  ) t2
  ON t1.country_id = t2.country_id AND t1.category = t2.category
SET t1.`order` = t2.`order`

As an aside note, you can remove order field from the table because this can calculated this on the fly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜