简体   繁体   English

根据另一个查询的 ORDER 更新列值

[英]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 #1 model我存储所有模型的地方

+---------------+---------+
| 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) #2 video_models_model连接modelvideo表(视频现在不相关)

+---------+---------+
| 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. 因此,我创建了新列 `order` 并将使用它来订购东西而不是上面的查询。 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? 然而,事实上在 99% 的情况下,一切都将保持原样,直到现在有没有办法使用上面的查询来更新“订单”列?

In other words I need some query which will create this in model table.换句话说,我需要一些查询来在model表中创建它。

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

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).侧节点: orderMySQL 中的保留字,因此列名的选择很糟糕(您需要在任何使用它的地方用反引号将其括起来)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM