mysql 神器 if 語句,儲存過程或遊標
BEGIN
declare key_list varchar(255) default '';
declare mykey varchar(255) default '';
declare int_flag int default 0;
declare done int default 0;
declare count_rs int default 0;
declare user_remainder DECIMAL(11,2) default 0.00;
declare re_rs int default 0;
/* 宣告遊標 */
DECLARE rs CURSOR FOR SELECT DISTINCT `name` FROM product_keylist;
/* 異常處理 */
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
/* 開啟遊標 */
#重新整理關鍵字表
CALL prod_product_keyword(f_db_name);
drop table if exists tmp_product_keylist_product;
create temporary table `tmp_product_keylist_product` (`name` varchar(128) not null,`number` int(11) not NULL, `proportion` DECIMAL(11,2)) DEFAULT CHARSET=utf8;
ALTER TABLE `kafka_data`.`tmp_product_keylist_product` ADD INDEX `name` USING HASH (`name` ASC);
#SELECT IFNULL(f_area,10);
SELECT f_area;
OPEN rs;
REPEAT
FETCH rs INTO mykey;
if not done THEN
IF model_id='all_event' THEN
select IFNULL(sum(`product_no`),0) INTO count_rs FROM `events` WHERE product_id
in (SELECT DISTINCT product_id FROM product WHERE product_keyword LIKE CONCAT("%",mykey,"%")
and
UNIX_TIMESTAMP(datetime) < UNIX_TIMESTAMP(endDate ) and UNIX_TIMESTAMP(datetime) > UNIX_TIMESTAMP(startDate )
and project=f_project and 1 and if(LENGTH(f_area)>0,project="111111",2)
) ;
ELSE
select IFNULL(sum(`product_no`),0) INTO count_rs FROM `events` WHERE product_id
in (SELECT DISTINCT product_id FROM product WHERE product_keyword LIKE CONCAT("%",mykey,"%")
and
UNIX_TIMESTAMP(datetime) < UNIX_TIMESTAMP(endDate ) and UNIX_TIMESTAMP(datetime) > UNIX_TIMESTAMP(startDate )
and project=f_project and 1 and if(LENGTH(f_area)>0,project="111111",2)
) and EVENT=model_id;
END IF;
#update product_keylist inner join (
#select count(`events`.user_id) as count_rs ,count(`events`.user_id)/user_total as user_remainder FROM `events`
#WHERE product_id in (SELECT DISTINCT product_id FROM product WHERE product_keyword LIKE CONCAT("%",mykey,"%"))
#) as c on product_keylist.name =mykey set product_keylist.number = c.count_rs ,product_keylist.proportion=user_remainder;
#SELECT count_rs as numberdjashdjksadhkj;
#set user_remainder=count_rs/user_total;
#create temporary table tmp_table(name varchar(10) not null,passwd char(6) not null)
#UPDATE product_keylist SET number=count_rs WHERE name=mykey;
INSERT IGNORE INTO tmp_product_keylist_product(`name`,`number`,`proportion`) VALUES (mykey,count_rs,user_remainder);
end if;
until done end REPEAT;
CLOSE rs;
SELECT `name`,number,proportion FROM tmp_product_keylist_product;
END