[英]MySQL update specific column
假設我有一個如下表:
id user_id name custom_field status
1 123 lee firstname 1
2 123 tan lastname 1
3 123 chan firstname 1
4 123 jackie lastname 1
5 123 justin firstname 0
6 123 wong lastname 0
7 223 kevin firstname 1
8 223 riley lastname 1
9 223 john firtname 1
10 223 poh lastname 1
我想做的是,foreach user_id我想確保只有1個姓和1個姓的狀態為1。 (所以基本上我想按id desc排序,並將那些不在前2位的狀態更新為1)。 我應該使用什么SQL腳本來完成此任務?
您可以使用以下update
查詢來執行此操作:
update t join
(select userid,
max(case when custom_field = 'firstname' then id end) as maxid_first,
max(case when custom_field = 'lastname' then id end) as maxid_last
from t
group by userid
) tt
on tt.userid = t.userid and t.id not in (tt.maxid_first, tt.maxid_last)
set status = 0;
編輯:
上面的內容不能保證至少有一個“ 1”。 為了那個原因:
update t join
(select userid,
max(case when custom_field = 'firstname' then id end) as maxid_first,
max(case when custom_field = 'lastname' then id end) as maxid_last
from t
group by userid
) tt
on tt.userid = t.userid
set status = (t.id in (tt.maxid_first, tt.maxid_last));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.