0
在下表中,我試圖用其總票數的總和更新每一行父母。在此選擇喜歡的總和()
這裏的一切都很好,除了我想用type = 10
中的一個SUM()
做事情,而不是我現在這樣做。現在,發生的情況是:如果type = 10
的總數發生變化,那麼父母的總數不會調整,而是會相加。我無法弄清楚如何在那裏添加sum()
。我來了這麼遠。你能幫我嗎?
如果你檢查我的存儲過程,你會看到它是如何工作的。
下面的東西很好。我不確定如何在sqlfiddle
上設置存儲過程來演示它。
我叫表與likesd
期望的結果
這些結果是由存儲過程以下
"id" "type" "path" "likes"
"1" "1" "0" "20"
"2" "1" "0" "20"
"3" "2" "1,2" "20"
"4" "2" "1,2,3" "20"
"5" "2" "1,2,3" "0"
"6" "3" "1,2,3,4" "0"
"7" "3" "1,2,3,4" "0"
"8" "4" "1,2,3,4" "20"
"9" "10" "1,2,3,4,8" "5" // These type 10 are books
"10" "10" "1,2,3,4,8" "5" // These type 10 are books
"11" "10" "1,2,3,4,8" "5" // These type 10 are books
"12" "10" "1,2,3,4,8" "5" // These type 10 are books
究竟做了這是存儲過程我使用
BEGIN
#---- Updater for like totals 21-11-2013
# Declare variables
DECLARE procId, procLikes INT(10);
DECLARE procPath VARCHAR(50);
DECLARE done INT DEFAULT 0;
# Declare cursor
DECLARE cur1 CURSOR FOR SELECT id, path, likes FROM testLikes WHERE type = 10;
# Declare Handle
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
# Open Cursor
OPEN cur1;
# Begin the Loop
the_loop: LOOP
FETCH cur1 INTO procId, procPath, procLikes;
IF done THEN
LEAVE the_loop;
END IF;
# Do some post processing
UPDATE testLikes t1 JOIN testLikes t2 ON FIND_IN_SET(t1.id, t2.path)
SET t1.likes = t1.likes + procLikes // Trying to add a sum(of all type = 10) here.
// Problem here is, New totals should be sum of all type = 10, but right now, it all adds up.
WHERE t2.id = procId;
END LOOP the_loop;
# Dummy select for MySql's bug
SELECT id INTO procId FROM testLikes where id = 1;
CLOSE cur1;
END
數據庫規範化的原則之一是不存儲計算值。 –
與您的評論相關 - 「如何在sqlfiddle上設置存儲過程來演示它。」檢查這個 在SqlFiddle上執行觸發器存儲過程。 Mysql http://stackoverflow.com/questions/12166380/execute-triggers-stored-procedures-on-sqlfiddle-mysql – Damodaran