我想从mySQL表中获得N个随机行。为了实现它,我使用临时表的存储过程(代码如下):
CREATE DEFINER=db_one
@%
PROCEDURE getRandomRecords
(IN cnt INT, IN section INT)
BEGIN
DROP TEMPORARY TABLE IF EXISTS randomRecords;
CREATE TEMPORARY TABLE randomRecords (
q_id
INT,
section_id
INT,
question_name
BLOB,
hint
BLOB,
question_type
INT,
content
BLOB,
chapter_id
INT,
UNIQUE KEY (q_id
)
) ;
loop_random :
LOOP
IF cnt < 1
THEN LEAVE loop_random;
END IF;
REPLACE INTO randomRecords
SELECT
r1.q_id,
r1.section_id,
r1.question_name,
r1.hint,
r1.question_type,
r1.content,
r1.chapter_id
FROM
questions AS r1
INNER JOIN
(SELECT
(
RAND() *
(SELECT
MAX(q_id)
FROM
questions)
) AS q_id) AS r2
WHERE r1.q_id >= r2.que_id
AND r1.section_id = section
AND r1.question_type = '1'
GROUP BY r1.chapter_id
ORDER BY r1.q_id ASC
LIMIT 1 ;
IF
ROW_COUNT() = 2
THEN SET cnt = cnt ;
ELSE SET cnt = cnt - 1 ;
END IF ;
END LOOP loop_random ;
SELECT
q_id,
section_id,
question_name,
hint,
question_type,
content,
chapter_id
FROM
randomRecords
ORDER BY chapter_id ASC,
q_id ASC ;
END$$
db_one
替换查询后带有ROW_COUNT()的'if else'语句负责控制是否将查询插入临时表或替换。如果行被替换,则counter(cnt值)保持其值,如果插入 - cnt值减少 它在使用mysql引擎5.1的数据库中应该工作 - 临时表在结果集中包含正好N行(过程中的cnt变量)。 当在mysql 5.5.8上使用数据库时,这个'if'语句似乎被忽略了 - 我得到的随机行数小于定义的N值。我怀疑ROW_COUNT()没有返回正确的值。 在使用REPLACE INTO查询后,是否有替代方法可以获得可靠的ROW_COUNT()值?