2

Actualmente esta query puede demorar más de 30 minutos. Lo que no entiendo es porque al eliminar una de estas tablas, ya sea gel6, gf6 o ger6 el rendimiento aumenta dramaticamente, demorándose menos de 500 ms.

¿Por qué es tan grande la diferencia de tiempo entre consultar 2 (< 500 ms) y 3 (> 30 minutos) de estas tablas?

 SELECT COUNT(*)
 FROM agroapp.ganado g
 INNER JOIN (SELECT gel5.ganado_id, gel5.estado_leche  
             FROM agroapp.ganado_estado_leche gel5  
             INNER JOIN (SELECT MAX(gel3.ganado_estado_leche_id) ganado_estado_leche_id  
                         FROM agroapp.ganado_estado_leche gel3  
                         INNER JOIN (SELECT gel.ganado_id, MAX(gel.created) created  
                                     FROM agroapp.ganado_estado_leche gel  
                                     WHERE gel.isactive = 'Y'  
                                     GROUP BY gel.ganado_id) gel2 ON (gel2.ganado_id = gel3.ganado_id AND gel2.created = gel3.created)  
                         WHERE gel3.isactive = 'Y'  
                         GROUP BY gel3.ganado_id) gel4 ON gel4.ganado_estado_leche_id = gel5.ganado_estado_leche_id  
            ) gel6 ON gel6.ganado_id = g.ganado_id
 INNER JOIN (SELECT gf5.ganado_id, gf5.fundo_id  
             FROM agroapp.ganado_fundo gf5  
             INNER JOIN (SELECT MAX(gf3.ganado_fundo_id) ganado_fundo_id  
                         FROM agroapp.ganado_fundo gf3  
                         INNER JOIN (SELECT gf.ganado_id, MAX(gf.created) created  
                                     FROM agroapp.ganado_fundo gf  
                                     WHERE gf.isactive = 'Y'  
                                     GROUP BY gf.ganado_id) gf2 ON (gf2.ganado_id = gf3.ganado_id AND gf2.created = gf3.created)  
                         WHERE gf3.isactive = 'Y'  
                         GROUP BY gf3.ganado_id) gf4 ON gf4.ganado_fundo_id = gf5.ganado_fundo_id  
            ) gf6 ON gf6.ganado_id = g.ganado_id
 INNER JOIN (SELECT ger5.ganado_id, ger5.estado_reproductivo  
             FROM agroapp.ganado_estado_reproductivo ger5  
             INNER JOIN (SELECT MAX(ger3.ganado_estado_reproductivo_id) ganado_estado_reproductivo_id  
                         FROM agroapp.ganado_estado_reproductivo ger3  
                         INNER JOIN (SELECT ger.ganado_id, MAX(ger.created) created  
                                     FROM agroapp.ganado_estado_reproductivo ger  
                                     WHERE ger.isactive = 'Y'  
                                     GROUP BY ger.ganado_id) ger2 ON (ger2.ganado_id = ger3.ganado_id AND ger2.created = ger3.created)  
                         WHERE ger3.isactive = 'Y'  
                         GROUP BY ger3.ganado_id) ger4 ON ger4.ganado_estado_reproductivo_id = ger5.ganado_estado_reproductivo_id  
            ) ger6 ON ger6.ganado_id = g.ganado_id
WHERE g.organizacion_id = 21

EDIT

CREATE TABLE agroapp.ganado_estado_leche
(
  ganado_estado_leche_id serial NOT NULL,
  organizacion_id integer NOT NULL,
  isactive character(1) NOT NULL DEFAULT 'Y'::bpchar,
  created timestamp without time zone NOT NULL DEFAULT now(),
  createdby numeric(10,0) NOT NULL,
  updated timestamp without time zone NOT NULL DEFAULT now(),
  updatedby numeric(10,0) NOT NULL,
  estado_leche character varying(80) NOT NULL,
  ganado_id integer NOT NULL,
  fecha_manejo timestamp without time zone NOT NULL,
  CONSTRAINT ganado_estado_leche_pk PRIMARY KEY (ganado_estado_leche_id),
  CONSTRAINT ganado_fk FOREIGN KEY (ganado_id)
      REFERENCES agroapp.ganado (ganado_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

CREATE TABLE agroapp.ganado_fundo
(
  ganado_fundo_id serial NOT NULL,
  organizacion_id integer NOT NULL,
  isactive character(1) NOT NULL DEFAULT 'Y'::bpchar,
  created timestamp without time zone NOT NULL DEFAULT now(),
  createdby numeric(10,0) NOT NULL,
  updated timestamp without time zone NOT NULL DEFAULT now(),
  updatedby numeric(10,0) NOT NULL,
  fundo_id integer NOT NULL,
  ganado_id integer NOT NULL,
  CONSTRAINT ganado_fundo_pk PRIMARY KEY (ganado_fundo_id),
  CONSTRAINT ganado_fk FOREIGN KEY (ganado_id)
      REFERENCES agroapp.ganado (ganado_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

CREATE TABLE agroapp.ganado_estado_reproductivo
(
  ganado_estado_reproductivo_id serial NOT NULL,
  organizacion_id integer NOT NULL,
  isactive character(1) NOT NULL DEFAULT 'Y'::bpchar,
  created timestamp without time zone NOT NULL DEFAULT now(),
  createdby numeric(10,0) NOT NULL,
  updated timestamp without time zone NOT NULL DEFAULT now(),
  updatedby numeric(10,0) NOT NULL,
  estado_reproductivo character varying(80) NOT NULL,
  ganado_id integer NOT NULL,
  fecha_manejo timestamp without time zone NOT NULL,
  CONSTRAINT ganado_estado_reproductivo_pk PRIMARY KEY (ganado_estado_reproductivo_id),
  CONSTRAINT ganado_fk FOREIGN KEY (ganado_id)
      REFERENCES agroapp.ganado (ganado_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)

CREATE TABLE agroapp.ganado
(
  ganado_id serial NOT NULL,
  organizacion_id integer NOT NULL,
  isactive character(1) NOT NULL DEFAULT 'Y'::bpchar,
  created timestamp without time zone NOT NULL DEFAULT now(),
  createdby numeric(10,0) NOT NULL,
  updated timestamp without time zone NOT NULL DEFAULT now(),
  updatedby numeric(10,0) NOT NULL,
  fecha_nacimiento timestamp without time zone NOT NULL,
  tipo_ganado character varying(80) NOT NULL,
  diio_id integer NOT NULL,
  fundo_id integer NOT NULL,
  raza_id integer NOT NULL,
  estado_reproductivo character varying(80) NOT NULL,
  estado_leche character varying(80),
  CONSTRAINT ganado_pk PRIMARY KEY (ganado_id),
  CONSTRAINT diio_fk FOREIGN KEY (diio_id)
      REFERENCES agroapp.diio (diio_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fundo_fk FOREIGN KEY (fundo_id)
      REFERENCES agroapp.fundo (fundo_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT raza_fk FOREIGN KEY (raza_id)
      REFERENCES agroapp.raza (raza_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION
)
6
  • Lo que preguntas es sumamente interesante y a la vez podría deberse a muchos factores. Es posible que coloques la estructura de las tablas, tipos de datos de las columnas, etc... el 4 dic. 2018 a las 18:11
  • 1
    Editado. Intentare colocar el EXPLAIN ANALYZE una vez finalice la query
    – danielctf
    el 4 dic. 2018 a las 18:30
  • Caramba!!! ¿de que cantidad de registros estamos hablando en dichas tablas?
    – Fly
    el 4 dic. 2018 a las 23:23
  • Una pregunta, por curiosidad, con la sentencia SELECT gel.ganado_id, MAX(gel.created) created ¿esperas obtener el ganado_id que tenga mayor valor en created ? lo digo porque creo que eso no será así y aunque no tenga que ver directamente con la velocidad de la consulta, si tiene relación con su utilidad,
    – Fly
    el 4 dic. 2018 a las 23:28
  • Ops!! veo que hablas de postgresql, quizá mi comentario del MAX no tiene sentido... bueno, dejo el comentario y obvialo si está fuera de lugar.
    – Fly
    el 4 dic. 2018 a las 23:40

1 respuesta 1

0

Tu query se ciclando con la 3era tabla en la condición:

ganado_estado_reproductivo_id = (max(ger3.ganado_estado_reproductivo_id))

Hace un aproximado de 138,042,608 ciclos para hacer la condición. Esto obvio es donde se traba el Query. Cuando normalmente los Querys se ciclan es porque se buscan datos repetidos, por ejemplo:

Tenemos una condición WHERE de la siguiente forma:

... WHERE (tb1_id = tb2_id);

postgres=# SELECT * FROM tb1;
 id 
----
  1
  1
  1
  2
  2
  3
  3
  3
  3

postgres=# SELECT * FROM tb2;
 id 
----
  1
  1
  1
  1
  1
  2
  2
  3
  3
  3
  3

Lo que hará el gestor como en tb1 es el que debe de igualarse con tb2, entonces tomará la primera fila de tb1 e irá a igualarla con las que encuentra en tb2, cada uno de estos procesos es un ciclo, aquí una imagen:

Ejemplo de ciclos por igualación

Donde cada color es un ciclo, fijate como se hacen 3 ciclos para igualar los unos, y se este repite aunque desde el primer ciclo la condición ya cumplió. Ahora multiplica eso por miles, tenemos 100 unos en tb1 que igualar con 10,000 en tb2, tenemos un mínimo de 100 ciclos, y 1 millón de filas extraídas. Tienes que asegurarte a través de la misma consulta que por lo general los joins se vayana uno a muchos.

Saludos!

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.