[英]Update column value based on ORDER of another query
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
连接model
和video
表(视频现在不相关)
+---------+---------+
| 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;
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).侧节点:
order
是MySQL 中的保留字,因此列名的选择很糟糕(您需要在任何使用它的地方用反引号将其括起来)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.