2013-03-20 26 views
0

我怎麼能在現場名稱中使用varables?使用變量字段名稱觸發(插入)

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 @[email protected]+1,`rank`=`rank`+1; 

END; 
| 

delimiter ; 

這個返回錯誤。如果@field使用`寫入,則查詢字段將是變量名稱,而不是變量值;

我不能老是用後CONCAT:

PREPARE stmt FROM @query; 
EXECUTE stmt; 
DEALLOCATE PREPARE stmt; 

,因爲這是動態SQL

我怎麼能賣出這個問題? 謝謝!

只有一個
+0

什麼是確切的錯誤信息? – Jocelyn 2013-03-20 16:52:30

+0

#1064,我不能老是用字段名沒有'%FIELD_NAME%',如果寫'@ field' - 一切都很好,但在結果查詢 - INSERT INTO ...'place_id','@ field')..哪裏變量是名稱不值 – DedMorozzz 2013-03-20 16:55:19

回答

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`[email protected]_cnt,`photo_cnt`=`photo_cnt`[email protected]_cnt,`video_cnt`=`video_cnt`[email protected]_cnt,`checkin_cnt`=`checkin_cnt`[email protected]_cnt,`tag_cnt`=`tag_cnt`[email protected]_cnt,`rank`=`rank`+1; 
相關問題