![](/img/trans.png)
[英]Mysql @count:= @count + 1 update column based on the sort order of another query
[英]Update column value based on ORDER of another query
大家好,我有兩張桌子。
#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
連接model
和video
表(視頻現在不相關)
+---------+---------+
| videoId | modelId |
+---------+---------+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
| 6 | 3 |
+---------+---------+
直到現在,當我需要模型時,我總是根據它們在視頻中使用的數量來訂購它們
SELECT * FROM model ORDER BY (
SELECT COUNT(*) FROM video_models_model WHERE modelId = model.id
) DESC;
換句話說,我需要一些查詢來在model
表中創建它。
+---------------+---------+ | id | name | order | +---------------+---------+ | 1 | Model #1 | 4 | | 2 | Model #2 | 3 | | 3 | Model #3 | 2 | | 4 | Model #4 | 1 | +---------------+---------+
您可以使用相關子查詢:
update model
set `order` = (
select count(*) from video_models_model vmm where vmm.modelid = model.id
)
側節點: order
是MySQL 中的保留字,因此列名的選擇很糟糕(您需要在任何使用它的地方用反引號將其括起來)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.