1. 程式人生 > >解決一個表中的資料由同表中兩欄位加權和得到(用觸發器解決)

解決一個表中的資料由同表中兩欄位加權和得到(用觸發器解決)

本次實驗一張表中的90%的資料由相關連的外表(b表)資料得到,即用觸發器得到。

https://blog.csdn.net/IT_95/article/details/84064958

那麼如何實現這張表裡面的資料得到一個總的值放在一個欄位呢?

第一時間的想法是在這張表(b表)裡面加觸發器實現,但是觸發器實現的是兩張表之間的資料變化。

最後的解決方案是在a表中觸發器裡面加上更新欄位資料指令

UPDATE db_corporatecreditscore SET IntegrityTotalScore=SolvencyIndicatorScore+ProfitabilityIndicatorScore+BusinessIndicatorScore+PerformanceIndicatorScore+DevelopmentIndicatorScore+TranceBackIndicatorScore;

連著上一個觸發器,一起執行就可以實現。

觸發器程式碼如下:

BEGIN
IF new.EventKind=1 THEN
UPDATE db_corporatecreditscore SET SolvencyIndicatorScore=SolvencyIndicatorScore+new.ScoreChange WHERE CreditCode=new.CreditCode;
END IF;
IF new.EventKind=2 THEN
UPDATE db_corporatecreditscore SET ProfitabilityIndicatorScore=ProfitabilityIndicatorScore+new.ScoreChange WHERE CreditCode=new.CreditCode;
END IF;
IF new.EventKind=3 THEN
UPDATE db_corporatecreditscore SET BusinessIndicatorScore=BusinessIndicatorScore+new.ScoreChange WHERE CreditCode=new.CreditCode;
END IF;
UPDATE db_corporatecreditscore SET IntegrityTotalScore=SolvencyIndicatorScore+ProfitabilityIndicatorScore+BusinessIndicatorScore+PerformanceIndicatorScore+DevelopmentIndicatorScore+TranceBackIndicatorScore;
END

資料庫表資訊如下

a表:

b表: