PostgreSQL inserts another field to implement an example after averaging a field

Source: Internet
Author: User

In the server load status monitoring, in order to avoid the load spikes caused by the useless alarm problem, I used to take the last 10 times the average load. This requirement was solved directly in Django, but the speed was not ideal after a period of running. The idea now is to have the database load the payload in another field when inserting new data, and then delete the code that calculates the average load for each server in Django, and the load value is changed to read the average directly. Because the database server is currently under a little pressure, the effect of increasing the performance after the trigger is not considered.

Calculate average

PostgreSQL calculates the average of SQL similar to the following:

With S as (select cast (load_15 as float) from Asset_serverstatus where sid_id=10 order by id DESC limit) Select AVG (loa D_15) from S
Trigger function
CREATE OR REPLACE FUNCTION fn_status_loadavg_insert () RETURNS trigger as$body$begin update asset_serverstatus set Load_av G= (with S as (select cast (load_15 as float) from Asset_serverstatus where sid_id=new.sid_id order by id desc limit) se Lect avg (load_15) from S) where Id=new.id;return new; END; $BODY $ LANGUAGE plpgsql VOLATILE cost 100;

Using Pgsql to write a trigger function, the basic idea is actually update.

Add a trigger to a table
CREATE TRIGGER Trg_status_loadavg_insert After insert in asset_serverstatus for each ROW EXECUTE PROCEDURE Fn_status_loada Vg_insert ();

In this way, the implementation of a field is averaged in the PostgreSQL database and then inserted into another field, depending on the condition.

Recorded.

Original address: http://www.sijitao.net/2030.html

PostgreSQL inserts another field to implement an example after averaging a field

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.