Skip to content
Advertisement

Update column value based on ORDER of another query

What I have:

Hi guys, I have two tables.

#1 model Where I store all models

+---------------+---------+
| id | name     |  order  |
+---------------+---------+
|  1 | Model #1 |   null  |
|  2 | Model #2 |   null  |
|  3 | Model #3 |   null  |
|  4 | Model #4 |   null  |
+---------------+---------+

#2 video_models_model which connect model and video table (video is unrelated now)

+---------+---------+
| videoId | modelId |
+---------+---------+
|     1   |    1    |
|     2   |    1    |
|     3   |    1    |
|     4   |    2    |
|     5   |    2    |
|     6   |    3    |
+---------+---------+

until now always when I needed models I ordered them based on in how many videos they are used in

SELECT * FROM model ORDER BY (
  SELECT COUNT(*) FROM video_models_model WHERE modelId = model.id
) DESC;

What I need:

However I found out that sometimes I need to manually change position of some models. Because of that I created new column `order` and will use it to order things instead of query above. However because of fact in 99% of cases everything will stay as it was until now is there a way to use query above to update `order` column?

In other words I need some query which will create this in model table.

+---------------+---------+
| id | name     |  order  |
+---------------+---------+
|  1 | Model #1 |    4    |
|  2 | Model #2 |    3    |
|  3 | Model #3 |    2    |
|  4 | Model #4 |    1    |
+---------------+---------+

Advertisement

Answer

You can use a correlated subquery:

update model
set `order` = (
    select count(*) from video_models_model vmm where vmm.modelid = model.id
)

Side node: order is a reserved word in MySQL hence a poor choice for a column name (you need to surround it with backticks everywhere you use it).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement