与foreach的Mysql存储过程

时间:2014-11-28 07:08:42

标签: php mysql stored-procedures

我是存储过程的新手

select distinct(movie_id) from movielist where mdate = ?

这返回movie_id(s),我需要为每个movie_id运行3个sql

foreach(movie_id){
    select count(*) as total_viewed from movielist where mdate = ? and movie_id = ? limit 1 //return only one value 
    select count(*) as total_viewed from movielist where mdate like ? and movie_id = ? limit 1 //return only one value
    select count(*) as total_viewed from movielist where mdate like ? and movie_id = ? limit 1 //return only one value

    //Then all the 3 value with movie_id and mdate insert at another table
}

现在如何为此编写存储过程......

2 个答案:

答案 0 :(得分:0)

我想你想根据每部电影显示观看次数

 select count(*) as total_viewed from movielist group by movie_id

这将显示基于movie_id的所有计数

 select count(*) as total_viewed from movielist group by mdate,movie_id 

将根据日期和电影向您显示所有计数..

你可以使用UNION ALL合并结果(只是一个提示,可以使用,不知道你真正想要的是什么)。

答案 1 :(得分:0)

您可以使用光标,但根本不需要。

我不确定您的存储过程应该做什么,但看起来想在特定日期提供前3部观看过的电影?如果只是这样做

select movie_id, count(*) as total_viewed from movielist 
where mdate = ? 
group by movie_id 
order by total_viewed desc 
limit 0,3;