今天在使用mysql 的update的時候碰到了這麼個麻煩的問題,簡記之。
問題起因:
我要給一張已經存在老使用者資料的表增加乙個字段,該錶為充值表,目前已有欄位為:
紅色的字段是我要新增上去的,用來標識使用者的本次充值是否為第一次充值,其實這個欄位不加上也無所謂,根據pay_time 和user_id其實就可以作sql查詢來統計相關功能了,但是為了以後統計的方便,我還是傾向於加上這麼乙個明了的字段。
因此,我就得給已經存在於資料庫的所有記錄來作判斷,判斷該條記錄是否是該使用者的首次充值。
於是我毫不猶豫,揮毫寫下了這麼乙個sql:
這個sql 也很容易理解,最裡面一層查詢出user_id 以及它對應的第一次充值時間update t_user_pay set is_first = 1
where pay_index in
(select pay.pay_index from t_user_pay as pay,
(select pay_index, min(pay_time) as m_time from t_user_pay
group by user_id
) as b
where pay.pay_time = b.m_time
);
第二層查詢出所有第一次充值的pay_index,然後由於pay_index是主鍵,因此在最外層使用update將pay_index所對應的is_first欄位置為 1,由此完成了我們的需求。
結果,悲劇了,mysql爆出了這麼乙個錯誤:
很簡單,update語句裡面的查詢條件不能是即將要被update的表。
原因就不分析了,這是mysql的內部機制。
那麼,在朋友的幫助下,使用了另外乙個方法,既然不能直接update是嘛,那好辦,我把select查詢出來之後的資料作臨時儲存,然後再進行update,這樣由於查詢條件不在原表了,這樣總沒問題了吧?
sql如下:
ok了,drop table if exists temp_pay ;
create temporary table temp_pay(pay_index bigint);
insert into temp_pay(pay_index)
select a.pay_index
from t_user_pay as a,
(select user_id,min(pay_time) min_time from t_user_pay group by user_id) as b
where a.user_id = b.user_id and a.pay_time=b.min_time;
update t_user_pay set is_first=1
where pay_index in(select pay_index from temp_pay);
drop table if exists temp_pay ;
執行成功。
不過這樣的方式效率不高,我暫時沒有想到其他更好的辦法,暫時記錄之。
今天碰到了乙個取 REMOTE USER 的問題
asp.net中,當設定web.config中認證方式為 windows 時,程式中 request.servervariables remote user 能取到值。但是設成 forms 或者 none的時候,就取不到了,request.servervariables remote user 返回...
原始碼編譯安裝runc碰到的乙個小坑
make all error 2編譯runc時,報錯,很明顯,是runc的乙個依賴庫github.com seccomp libseccomp golang的錯誤。於是單獨編譯安裝該庫,同樣丟擲 mismatched types c.uint32 t and c.uint 這個錯誤。檢視原始碼 se...
乙個update差點引發的血案
三條語句如下 因為保密原因表名都是處理過的測試表名 update uct user abc t,uct udc t1 set t.user type teacher where t1.id t.user id and t1.user type 1 update uct user abc t,uct ...