我对mysql存储过程和变量有疑问;
表名:es_adwords 字段:id#image_source#image_link#computer_id#is_all_pc#image_state #flag_size
我想创建应该搜索computer_id = {pc_number}和image_state = 0的存储过程。
如果不是,则存储过程应返回等于is_all_pc = 1。
DELIMITER $$
DROP PROCEDURE IF EXISTS `GetAdwordsBanner` $$
DELIMITER $$
CREATE PROCEDURE `GetAdwordsBanner`(IN compid INT)
BEGIN
SET @result_id := 0;
SELECT @result_id := id FROM es_adwords WHERE image_state = 1 AND computer_id = compid ORDER BY id DESC LIMIT 0,1;
IF (@result_id != 0) THEN
SELECT image_source,image_link,banner_size FROM es_adwords WHERE image_state = 1 AND computer_id = compid ORDER BY id DESC LIMIT 0,1;
ELSE
SELECT image_source,image_link,banner_size FROM es_adwords WHERE image_state = 1 AND is_all_pc = 1 ORDER BY id DESC LIMIT 0,1;
END IF;
END $$
DELIMITER ;
真诚的你......
答案 0 :(得分:0)
你的逻辑有问题。我会把它重写为:
DELIMITER $$
CREATE PROCEDURE `GetAdwordsBanner`(IN compid INT)
BEGIN
-- use a local variable instead of a user variable
DECLARE result_count INT;
-- count how many rows are matching
SELECT COUNT(*) INTO result_id FROM es_adwords WHERE image_state = 1 AND computer_id = compid;
-- if there are matches
IF result_count > 0 THEN
-- return the first matching row
SELECT image_source,image_link,banner_size FROM es_adwords WHERE image_state = 1 AND computer_id = compid ORDER BY id DESC LIMIT 0,1;
ELSE
-- return the default one
SELECT image_source,image_link,banner_size FROM es_adwords WHERE image_state = 1 AND is_all_pc = 1 ORDER BY id DESC LIMIT 0,1;
END IF;
END $$
DELIMITER ;
这应该有用。