SQL function very slow compared to query without function wrapper

前端 未结 2 1432
难免孤独
难免孤独 2020-12-20 15:43

I have this PostgreSQL 9.4 query that runs very fast (~12ms):

SELECT 
  auth_web_events.id, 
  auth_web_events.time_stamp, 
  auth_web_events.description, 
          


        
2条回答
  •  眼角桃花
    2020-12-20 16:21

    You will get better performance by making this query dynamic and using plpgsql.

    CREATE OR REPLACE FUNCTION get_web_events_by_userid(uid int) RETURNS TABLE(
        id int,
        time_stamp timestamp with time zone,
        description text,
        origin text,
        userlogin text,
        customer text,
        client_ip inet
         ) AS $$
    BEGIN
    
    RETURN QUERY EXECUTE
    'SELECT 
      auth_web_events.id, 
      auth_web_events.time_stamp, 
      auth_web_events.description, 
      auth_web_events.origin,  
      auth_user.email AS user, 
      customers.name AS customer,
      auth_web_events.client_ip
    FROM 
      public.auth_web_events, 
      public.auth_user, 
      public.customers
    WHERE 
      auth_web_events.user_id_fk = auth_user.id AND
      auth_user.customer_id_fk = customers.id AND
      auth_web_events.user_id_fk = ' || uid ||
    'ORDER BY
      auth_web_events.id DESC;'
    
    END;
    $$ LANGUAGE plpgsql;
    

提交回复
热议问题