Pergunta

Aqui está a declaração preparada pelo MySQL

SELECT 
    ag.`attendance_type`,
    ag.`description`,
    COUNT(a.`attendance`) attendance_count 
FROM
    `ems_attendance` a 
    RIGHT JOIN `ems_att_group` ag 
        ON ag.`id` = a.`attendance` 
        AND a.`added_date` BETWEEN '2011-06-01' 
        AND '2011-06-17' 
        AND a.`users_id` = '9' 
GROUP BY a.`attendance` 
ORDER BY ag.`id`;

e procedimento de armazenamento equivalente

DELIMITER $$

DROP PROCEDURE IF EXISTS `users_attendance_report` $$

CREATE PROCEDURE `users_attendance_report` (
    IN users_id INT,
    IN start_date DATE,
    IN end_date DATE
) 
BEGIN
    SELECT 
        ag.`attendance_type`,
        ag.`description`,
        COUNT(a.`attendance`) attendance_count 
    FROM
        `ems_attendance` a 
        RIGHT JOIN `ems_att_group` ag 
            ON ag.`id` = a.`attendance` 
            AND a.`added_date` BETWEEN start_date 
            AND end_date 
            AND a.`users_id` = users_id 
    GROUP BY a.`attendance` 
    ORDER BY ag.`id` ;
END $$

DELIMITER;

Depois de executar a consulta, os dois geram os mesmos resultados.

Array
(
    [0] => stdClass Object
        (
            [attendance_type] => present
            [description] => Present
            [attendance_count] => 10
        )

    [1] => stdClass Object
        (
            [attendance_type] => absent
            [description] => Absent
            [attendance_count] => 2
        )

    [2] => stdClass Object
        (
            [attendance_type] => other
            [description] => Other
            [attendance_count] => 0
        )

    [3] => stdClass Object
        (
            [attendance_type] => dayoff
            [description] => Day Off
            [attendance_count] => 2
        )

)

Eu olho atentamente para o tempo de execução, ambos são iguais.Quando e onde um é melhor e mais rápido do que o outro?

Foi útil?

Solução

"Faster" and "better" are not necessarily aligned. Please see this recent similar SO question, and consider these attributes of a solution:

  • maintainable (readable, skills requirements - who can work on this code)
  • testable
  • releasable
  • flexible
  • portable

Generally speaking, stored procedures are faster, but fail on every other metric.

Outras dicas

I think in your case it doesn't matter if you run the query standalone or as part of stored procedure. A procedure is nice in situations where you've got a query batch to perform. Therefore, for your query it's best to run standalone.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top