如何在字段名称中使用变量?
delimiter |
CREATE TRIGGER update_expression_counter BEFORE INSERT ON remake_town_expressions
FOR EACH ROW BEGIN
SET @type := NEW.`type`;
SET @user_id := NEW.user_id;
SET @user_profile_id := NEW.user_profile_id;
SET @country_iso := NEW.country_iso;
SET @place_id := NEW.`place_id`;
SET @city_id := NEW.`city_id`;
SET @field := 'comment_cnt';
SELECT CASE @type
WHEN 'comment' THEN 'comment_cnt'
WHEN 'photo' THEN 'photo_cnt'
WHEN 'video' THEN 'video_cnt'
WHEN 'tag' THEN 'tag_cnt'
WHEN 'checkin' THEN 'checkin_cnt'
END
INTO @field;
INSERT INTO `remake_town_counter` (`user_id`,`user_profile_id`,`country_iso`,`city_id`,`place_id`, @field)
VALUES (@user_id,@user_profile_id,@country_iso,@city_id,@place_id,1) ON DUPLICATE KEY UPDATE @field=@field+1,`rank`=`rank`+1;
END;
|
delimiter ;
此返回错误。如果@field用`写,则查询字段将是变量名,而不是变量值;
我不能在以后使用concat:
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
,因为这是动态的sql
我怎么能卖掉这个问题? 谢谢!
答案 0 :(得分:0)
只找到一个解决方案: 在查询中写入所有字段和所需的字段更新+1; 我的结果
SET @comment_cnt := CASE WHEN @type = 'comment' THEN 1 ELSE 0 END;
SET @photo_cnt := CASE WHEN @type = 'photo' THEN 1 ELSE 0 END;
SET @video_cnt := CASE WHEN @type = 'video' THEN 1 ELSE 0 END;
SET @tag_cnt := CASE WHEN @type = 'tag' THEN 1 ELSE 0 END;
SET @checkin_cnt := CASE WHEN @type = 'checkin' THEN 1 ELSE 0 END;
-- update user count actions in the place
INSERT INTO `remake_town_counter` (`user_id`,`user_profile_id`,`country_iso`,`city_id`,`place_id`, `comment_cnt`,`photo_cnt`,`video_cnt`,`checkin_cnt`,`tag_cnt`,`rank`)
VALUES (@user_id,@user_profile_id,@country_iso,@city_id,@place_id,@comment_cnt,@photo_cnt,@video_cnt,@checkin_cnt,@tag_cnt,1)
ON DUPLICATE KEY UPDATE
`comment_cnt`=`comment_cnt`+@comment_cnt,`photo_cnt`=`photo_cnt`+@photo_cnt,`video_cnt`=`video_cnt`+@video_cnt,`checkin_cnt`=`checkin_cnt`+@checkin_cnt,`tag_cnt`=`tag_cnt`+@tag_cnt,`rank`=`rank`+1;