>데이터 베이스 >MySQL 튜토리얼 >MySQL存储过程获取记录排名(一般用于投票系统)

MySQL存储过程获取记录排名(一般用于投票系统)

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB원래의
2016-06-07 14:57:341174검색

MySQL存储过程获取记录排名(一般用于投票系统) 原理 计算当前学校的票数,暂且记作a 计算票数大于自己的学校数目,暂且记作b,如果b=0,则自己票数排名第一 计算票数小于自己的学校数目,暂且记作c,如果c=0,则自己票数排名最后 如果b!=0c!=0,那么b+c就是

MySQL存储过程获取记录排名(一般用于投票系统)
原理
计算当前学校的票数,暂且记作a
计算票数大于自己的学校数目,暂且记作b,如果b=0,则自己票数排名第一
计算票数小于自己的学校数目,暂且记作c,如果c=0,则自己票数排名最后
如果b != 0 && c != 0,那么b+c就是自己的票数排名
CREATE PROCEDURE `get_rank`(IN `school` INT)
BEGIN
SET @votes = (SELECT COUNT(tcl_vote.vote_id) AS counts FROM tcl_works LEFT JOIN tcl_vote ON tcl_vote.works_id = tcl_works.works_id WHERE tcl_works.school_id=school);
SET @gt = (
SELECT
COUNT(*)
FROM
(
SELECT
tcl_works.school_id,
COUNT(tcl_vote.vote_id) AS votes
FROM
tcl_works
LEFT JOIN tcl_vote ON tcl_vote.works_id = tcl_works.works_id
GROUP BY
tcl_works.school_id
HAVING
votes > @votes
ORDER BY
votes DESC
)
AS xxx
);
IF @gt = 0
THEN
SET @rank = 1;
SELECT @rank AS rank;
ELSE
SET @lt = (
SELECT
COUNT(*)
FROM
(
SELECT
tcl_works.school_id,
COUNT(tcl_vote.vote_id) AS votes
FROM
tcl_works
LEFT JOIN tcl_vote ON tcl_vote.works_id = tcl_works.works_id
GROUP BY
tcl_works.school_id
HAVING
votes < @votes
ORDER BY
votes DESC
)
AS xxx
);
IF @lt = 0
THEN
SET @rank =(SELECT COUNT(*) FROM tcl_school LIMIT 1);
SELECT @rank AS rank;
ELSE
SET @rank = (@gt+@lt);
SELECT @rank AS rank;
END IF;
END IF;
END;

call get_rank(1)
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.