mysql定時任務和存儲過程的小例子
知識
07-14
emmm其實網上優秀的文章有很多,並且mysql也有官方文檔,寫這個是相當於記錄自己的經歷吧。
上面說升級的那裡,是要執行一個定時任務,每三天執行一次。然後情況如下:
一個商品表,商品有一個id的屬性,然後每個商品有關鍵詞信息,對應一個商品-關鍵詞中間表(通過商品id、關鍵詞id為一個主鍵),關鍵詞其他信息又存放在另一個表裡面,這時候要統計商品表的關鍵詞數量,因為實時統計耗費的時間太多了,只能通過定期更新的方式,並作為商品的一個屬性。
商品表的每個商品都要進行更新的話,就用到游標來處理,大概思路是這樣,首先從商品表獲取每個商品的id形成一個集合,然後用游標和while循環遍歷每個id,把id拿去中間表裡面找到所有關鍵詞id,再把這些關鍵詞id去關鍵詞表查找得出關鍵詞的總數(一個商品對應多個關鍵詞,需要把這些關鍵詞的數量統計出來)
其實重點在於游標的應用和存儲過程的應用(語法挺重要的),貼上代碼:
- DELIMITER $$
- CREATE
- /*[DEFINER = { user | CURRENT_USER }]*/
- PROCEDURE `test`.`yinliucount_new`()
- /*LANGUAGE SQL
- | [NOT] DETERMINISTIC
- | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL DATA }
- | SQL SECURITY { DEFINER | INVOKER }
- | COMMENT "string"*/
- BEGIN
- DECLARE goodsid VARCHAR(255);
- DECLARE keywordgoodsid VARCHAR(255);
- DECLARE yinliuc INT;
- DECLARE done INT DEFAULT 0;
- DECLARE cur CURSOR FOR SELECT goodsurlid FROM store_goods;
- DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
- OPEN cur;
- FETCH cur INTO goodsid;
- WHILE done != 1 DO
- SET keywordgoodsid = SUBSTRING_INDEX(goodsid,"_",-1);
- SELECT COUNT(*) INTO yinliuc FROM (SELECT * FROM store_allkeyword WHERE keywordid IN(SELECT keywordid FROM store_goods_keyword WHERE goodsurlid = keywordgoodsid) GROUP BY keyword_name)d;
- IF yinliuc IS NOT NULL THEN
- UPDATE store_goods SET yinliu_count = yinliuc WHERE goodsurlid = goodsid;
- END IF;
- FETCH cur INTO goodsid;
- END WHILE;
- CLOSE cur;
- END$$
- DELIMITER ;
然後用 新建一個定時任務,注釋都是一些例子
- DELIMITER $$
- -- SET GLOBAL event_scheduler = ON$$ -- required for event to execute but not create
- CREATE /*[DEFINER = { user | CURRENT_USER }]*/ EVENT `weanalysis`.`d`
- ON SCHEDULE EVERY 2 DAY STARTS "2018-07-13 16:00:00"
- ON COMPLETION PRESERVE
- ENABLE
- /* uncomment the example below you want to use */
- -- scheduleexample 1: run once
- -- AT "YYYY-MM-DD HH:MM.SS"/CURRENT_TIMESTAMP { + INTERVAL 1 [HOUR|MONTH|WEEK|DAY|MINUTE|...] }
- -- scheduleexample 2: run at intervals forever after creation
- -- EVERY 1 [HOUR|MONTH|WEEK|DAY|MINUTE|...]
- -- scheduleexample 3: specified start time, end time and interval for execution
- /*EVERY 1 [HOUR|MONTH|WEEK|DAY|MINUTE|...]
- STARTS CURRENT_TIMESTAMP/"YYYY-MM-DD HH:MM.SS" { + INTERVAL 1[HOUR|MONTH|WEEK|DAY|MINUTE|...] }
- ENDS CURRENT_TIMESTAMP/"YYYY-MM-DD HH:MM.SS" { + INTERVAL 1 [HOUR|MONTH|WEEK|DAY|MINUTE|...] } */
- /*[ON COMPLETION [NOT] PRESERVE]
- [ENABLE | DISABLE]
- [COMMENT "comment"]*/
- DO
- BEGIN
- CALL test.`yinliucount_new`;
- END$$
- DELIMITER ;
然後就設置好了,其他具體的語法,是要去看mysql官方文檔還有別人的博客的,我就不班門弄斧了,這個只是一個參考的小例子。
※較全Vim快捷鍵鍵點陣圖(入門到進階)
※C++ 中指針和引用的區別
TAG:程序員小新人學習 |