簡體   English   中英

根據MySQL中另一列分組的另一列的順序更新列

[英]Update columns based on order of another column grouped by another column in MySQL

這是我的桌子:

在此處輸入圖片說明

我需要使用更新查詢來更新此表,以便在更新查詢后,我的表應為:

在此處輸入圖片說明

即)對於common_id,我需要通過訂購該common_id的位置來更新從1開始的位置。

這只是一個示例表。 我的實際表有數百萬個條目。

如果將id列設置為自動遞增,則可以對同一表使用帶有連接子句的更新查詢

update table1 a
join (
  select a.id,a.common_id,count(*) pos
  from table1 a
  left join table1 b on a.common_id = b.common_id
  and a.id >= b.id
  group by a.id, a.common_id
) b using(id,common_id)
set a.position = b.pos

演示

如果僅出於選擇目的,則可以將其用作

select a.id,a.common_id,count(*) pos
from table1 a
left join table1 b on a.common_id = b.common_id
and a.id >= b.id
group by a.id, a.common_id

演示

注釋后編輯, 無論哪個位置最小,位置都應為1

在您發表評論之后,您可以按照排名標准進行更新,但這完全取決於common_id,position是否唯一,這意味着每個common_id應該有唯一的排名

選擇

select a.common_id,a.position,count(*) pos
from table1 a
left join table1 b on a.common_id = b.common_id
and a.position >= b.position
group by a.common_id,a.position
order by a.common_id

更新

update table1 a
join (
  select a.common_id,a.position,count(*) pos
  from table1 a
  left join table1 b on a.common_id = b.common_id
  and a.position >= b.position
  group by a.common_id,a.position
) b using(common_id,position)
set a.position = b.pos

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM