MySQL數(shù)據(jù)庫中正確執(zhí)行批量更新計數(shù)器
以下的文章主要向大家描述的是MySQL數(shù)據(jù)庫中執(zhí)行批量更新計數(shù)器的實際操作步驟 ,假設(shè)我們的MySQL數(shù)據(jù)庫有一個計數(shù)器,此計數(shù)器需要我們對其重新統(tǒng)計,那么我們應(yīng)如何對其進行設(shè)置呢?
應(yīng)用場景,比如說有一個商場,每賣一個產(chǎn)品都產(chǎn)生一個流水,然后我們需要知道每筆流水是該產(chǎn)品第幾次出售的,這樣說可能不明白,我拿一個詳細的數(shù)據(jù)舉例吧。
- recordID,productID,productType,sellDate,counter
- 1, 1, 1, '2010-1-15 15:20:10' 0
- 2, 1, 2, '2010-1-15 15:20:10' 1
- 3, 2, 1, '2010-1-15 15:20:10' 0
- 4, 2, 1, '2010-1-15 15:20:10' 1
上面這個數(shù)據(jù)是一些撒氣數(shù)據(jù),包括記錄的流水號,產(chǎn)品的編號,產(chǎn)品的類型,銷售的時間,計數(shù)器。一般來說,計數(shù)器我們首先我會想到自增,但這而肯定是不可能使用自增長的。
我最初的時候,嘗使用這樣的代碼:
- update t_product set t_counter = (select max(counter)
- from t_product where productid = 1 and productType = 1) + 1
- where where productid = 1 and productType = 1
但是MySQL報錯,上網(wǎng)一查,MySQL數(shù)據(jù)庫不支持這種寫法,呵呵,我對MySQL完全不熟悉。記得以前在sql server用過游標(biāo),然后也試試查找游標(biāo),經(jīng)過n次google與百度,最終搞定這個難題。
我本身對MySQL完全是個外行,就連注釋也不知道怎么注釋的,現(xiàn)在終于知道有三種寫法的,而--的注釋后面是要空一格的,所以代碼寫得性能什么的就不敢說了,只是實現(xiàn)了這個功能,希望對有同樣需求的朋友有用。
呵,還學(xué)到一點,declare只能寫在最前面。
看最終的代碼:
- CREATE PROCEDURE p_resetCounter ()
- BEGIN
- DECLARE productID INT;
- DECLARE type INT;
- DECLARE tmpCount INT;
- DECLARE stopFlag int;
使用游標(biāo)
- DECLARE cur cursor for SELECT COUNT(*), productID, productType FROM
- t_product GROUP BY productID, productType;
- DECLARE CONTINUE HANDLER FOR NOT FOUND set stopFlag=1;
如果找不到記錄,則設(shè)置stopFlag=1
定義變量及創(chuàng)建臨時表
- CREATE TEMPORARY TABLE tmp_Counter(
- recordID int not null,
- Counter int not null
- )TYPE = HEAP;
打開游標(biāo)
- open cur;
- REPEAT
- fetch cur into tmpCount, productID, type;
- SET @id = -1;
- INSERT INTO tmp_Counter
- (SELECT recordID, (@id := @id + 1) counter
- from t_product WHERE productIDproductID = productID AND productType = type)
- ORDER BY ts_Date ASC;
- UNTIL stopFlag = 1
- END REPEAT;
- close cur;
關(guān)閉游標(biāo)
- UPDATE t_product, tmp_Counter SET counter = tmp_Counter.Counter
- WHERE recordID = tmp_Counter.recordID;
- -- SELECT * FROM tmp_Counter;
- DROP TABLE tmp_Counter;
刪除臨時表
- END;
以上的相關(guān)內(nèi)容就是對MySQL數(shù)據(jù)庫中如何批量更新計數(shù)器的介紹,望你能有所收獲。
【編輯推薦】