0

如何在字段名称中使用变量?

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

我怎样才能卖掉这个问题?谢谢!

4

1 回答 1

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;
于 2013-03-21T13:25:18.183 回答