存储过程和准备语句之间的MySQL性能比较

时间:2011-06-17 06:24:48

标签: php mysql sql stored-procedures database-performance

这是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`;

和等效的存储过程

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;

运行查询后,两者都输出相同的结果。

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
        )

)

我仔细研究执行时间,两者都是一样的。何时何地比另一个更好更快?

2 个答案:

答案 0 :(得分:4)

“更快”和“更好”不一定是一致的。请参阅this recent similar SO问题,并考虑解决方案的这些属性:

  • 可维护(可读,技能要求 - 谁可以使用此代码)
  • 可测试
  • 可释放
  • 灵活
  • 便携式

一般来说,存储过程更快,但每个其他指标都失败。

答案 1 :(得分:2)

我认为在您的情况下,如果您单独运行查询或作为存储过程的一部分运行,则无关紧要。在您要执行查询批处理的情况下,过程很好。因此,对于您的查询,最好独立运行。