当我多次使用一个搜索条件时,如何在mysql存储过程中优化我的代码?

时间:2015-10-28 16:49:40

标签: mysql sql

在我的mysql存储过程中,我必须搜索昨天创建的数据。现在我的代码在这里:

DECLARE  v_CurrentDate, v_LastDate datetime ;
set v_CurrentDate=curdate();
set v_LastDate=date_sub(curdate(),interval 1 day);
-- student
select count(*) from student where where createtime>=v_LastDate
and createtime< v_CurrentDate;
-- worker
select count(*) from worker where where createtime>=v_LastDate
and createtime< v_CurrentDate;
 -- food
select count(*) from food where where createtime>=v_LastDate
and createtime< v_CurrentDate;
-- vegetables
select count(*) from vegetables where where createtime>=v_LastDate
and createtime< v_CurrentDate;

我有四个相同的条件,我可以编写更优化的代码吗?

2 个答案:

答案 0 :(得分:1)

在过程语言中,包装SQL,tableswhere clauses不是一等公民。您不能将它们分配给变量,从函数返回它们,将它们作为参数传递或连接它们。

所以不,你不能优化它,除非你使用字符串处理或动态sql从更简洁的源生成这个程序。这是射击你的好方法。

答案 1 :(得分:0)

没有没有好方法来优化此代码。您可以更改一些内容,以便减少代码,但运行速度较慢或难以维护。这通常是SQL的情况,它将需要更多的代码而不是必要的代码。你正在做的是正确的做法。