我正在尝试编写一个将触发相同选择查询的过程,直到结果数大于0.如果"间隔2小时"返回0记录,则应使用"间隔4小时"标准,如果仍有没有记录被提取,那么lastupdate> current_date()应该在where子句中使用.
这些是过程中使用的2个基本查询.
select sql_calc_found_rows id from sometable where lastupdate > date_sub(now(), interval 2 hour) limit 10;
select found_rows();
+--------------+
| found_rows() |
+--------------+
| 41 |
+--------------+
Run Code Online (Sandbox Code Playgroud)
以下程序是否正确?这是写SP的正确方法吗?我如何在PHP代码中使用结果?
delimiter $$
create procedure mytest3()
begin
declare myvar int;
select sql_calc_found_rows id
from sometable
where lastupdate > date_sub(now(), interval 2 hour)
limit 10;
select found_rows() into myvar;
if (myvar > 0)
then select 'Found in 2 hours';
else
select sql_calc_found_rows id
from sometable
where lastupdate > date_sub(now(), interval 4 hour)
limit 10;
select found_rows() into myvar;
if (myvar > 0)
then select 'Found in 4 hours';
else
select sql_calc_found_rows id
from sometable
where lastupdate > current_date()
limit 10;
end if;
end if;
end$$
Run Code Online (Sandbox Code Playgroud)
我发现,当你在文本的标题和正文中都要求循环时,你真正要做的就是获取"在过去X小时内修改过的行"的列表,其中最小的X返回一些(非空)行集...
这是实现这一目标的一种方法:
delimiter $$
create procedure recently_modified_rows()
begin
declare tablelastupdate int; -- how many hours ago table was last updated.
declare showperiod datetime; -- what time interval to show
declare showtext text; -- text describing time interval
select hour(timediff(now(), max(lastupdate))) into tablelastupdate
from sometable;
if(tablelastupdate < 2)
set showperiod = time_sub(now(), interval 2 hours);
set showtext = "modified in the last 2 hours";
elseif (tablelastupdate < 4)
set showperiod = time_sub(now(), interval 4 hours);
set showtext = "modified in the last 4 hours";
else
set showperiod = current_date();
set showtext = "modified today";
end if
select sql_calc_found_rows id,
showtext description
from sometable
where lastupdate > showperiod
limit 10;
end$$
Run Code Online (Sandbox Code Playgroud)
并从PHP调用它:
$query = mysql_query("call recently_modified_rows()") or die( mysql_error() );
$numrows = mysql_numrows($query);
if ($numrows != 0)
{
/* print out what time interval we used */
$description = mysql_result($query, 0, 'description');
echo "Found $numrows rows $description";
/* print out the rows */
while ($row = mysql_fetch_array($query))
{
echo "Id: {$row['id']}";
}
}
else
{
/* happens only if there were no records modified in any of the three versions */
echo "no records were modified in the last 2 hours, 4 hours, or today";
}
Run Code Online (Sandbox Code Playgroud)