Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 2nd, 2012  |  syntax: None  |  size: 1.27 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. MySQL - How to update atable based on an internal ordering of the table
  2. SELECT * FROM mytable ORDER BY country_id, category
  3.        
  4. +------------+----------+-------+
  5. | country_id | category | order |
  6. +------------+----------+-------+
  7. |          1 |        A |     0 |
  8. |          1 |        B |     0 |
  9. |          1 |        F |     0 |
  10. |          3 |        A |     0 |
  11. |          3 |        C |     0 |
  12. |          5 |        B |     0 |
  13. |          5 |        L |     0 |
  14. |          5 |        P |     0 |
  15. +------------+----------+-------+
  16.        
  17. +------------+----------+-------+
  18. | country_id | category | order |
  19. +------------+----------+-------+
  20. |          1 |        A |     1 |
  21. |          1 |        B |     2 |
  22. |          1 |        F |     3 |
  23. |          3 |        A |     1 |
  24. |          3 |        C |     2 |
  25. |          5 |        B |     1 |
  26. |          5 |        L |     2 |
  27. |          5 |        P |     3 |
  28. +------------+----------+-------+
  29.        
  30. UPDATE mytable t1
  31.   JOIN (
  32.     SELECT t1.country_id, t1.category, COUNT(*) `order`
  33.     FROM mytable t1
  34.     LEFT JOIN mytable t2
  35.       ON t2.country_id = t1.country_id AND t2.category <= t1.category
  36.     GROUP BY
  37.       t1.country_id, t1.category
  38.   ) t2
  39.   ON t1.country_id = t2.country_id AND t1.category = t2.category
  40. SET t1.`order` = t2.`order`