作者官方网站:http://www.wxl568.cn
本站首页《存储过程方面,sql、分组、排序、动态计算数据等》知识
下面是本站实战的文章首页排序sql计算
-- sql 删除存储过程
drop procedure if exists p_js_ranking;
下面存储过程
delimiter //
create procedure p_js_ranking() -- 创建存储过程
begin -- 开始存储过程
-- COMMIT; -- 提交事务
declare ttypeT varchar(32); -- 自定义变量1
declare countnT INT; -- 自定义变量2
DECLARE done INT DEFAULT FALSE; -- 自定义控制游标循环变量,默认false
DECLARE number1 INT DEFAULT 0;
DECLARE My_Cur CURSOR FOR (
SELECT
a.t_type,a.countn from(
select t_type, count(t_type) countn from home_page_cont group by t_type order by countn desc
)a
); -- 定义游标并输入结果集
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; -- 绑定控制变量到游标,游标循环结束自动转true
TRUNCATE TABLE home_page_cont;
insert into home_page_cont (cont_id,t_title,t_url,t_type,t_type_name)
--下面sql语句二选一
-- 获取最新的3条
SELECT a.id cont_id,a.t_title,a.t_url,a.t_type,a.t_type_name from wxl_content a where exists (select count(*) from wxl_content where t_type = a.t_type and id > a.id having Count(*) < 3) order by a. update_date
-- 获取最新的3条,但时间同一秒相同保持,数量不是3条,主要时间
SELECT a.id cont_id,a.t_title,a.t_url,a.t_type,a.t_type_name
FROM wxl_content a
LEFT JOIN wxl_content b ON a.t_type=b.t_type AND a.update_date< b.update_date AND b.is_fig=1
WHERE a.is_fig=1
GROUP BY a.id,a.t_type,a.update_date
HAVING COUNT(b.id)< 2
ORDER BY a.t_type,a.update_date DESC;
OPEN My_Cur; -- 打开游标
myLoop: LOOP -- 开始循环体,myLoop为自定义循环名,结束循环时用到
FETCH My_Cur into ttypeT, countnT; -- 将游标当前读取行的数据顺序赋予自定义变量
IF done THEN -- 判断是否继续循环
LEAVE myLoop; -- 结束循环
END IF;
-- 自己要做的事情,在 sql 中直接使用自定义变量即可
SET number1 = number1+1;
update home_page_cont set ranking=number1 where t_type=ttypeT ;-- 左更新排序字段为首页做排序显示
COMMIT; -- 提交事务
END LOOP myLoop; -- 结束自定义循环体
CLOSE My_Cur; -- 关闭游标
END;// -- 结束存储过程
-- sql 执行存储过程
call p_js_ranking();
作者官方网站:http://www.wxl568.cn