I am developing a small jumbled-words game for users on a PtokaX DC hub I manage. For this, I'm storing the list of words inside a MySQL table. Table schema is as follows:
CREATE TABLE `jumblewords` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`word` CHAR(15) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `word` (`word`)
)
COMMENT='List of words to be used for jumble game.'
COLLATE='utf8_general_ci'
ENGINE=MyISAM;
Now, in the game-engine; I want to fetch 20 words as a string randomly. This I can achieve with a query similar to this:
SELECT GROUP_CONCAT(f.word SEPARATOR ', ' )
FROM ( SELECT j.word AS word
FROM jumblewords j
ORDER BY RAND()
LIMIT 20) f
but I have to execute this statement everytime the list expires(all 20 words have been put before user).
Can I modify this query so that I can fetch more than one row with the results as generated from the query I have above?
Probably an easier way to solve this problem is by storing the random words in a temporary table and later extract the values. A stored procedure would be perfect for that.
DELIMITER //
DROP PROCEDURE IF EXISTS sp_jumblewords //
CREATE PROCEDURE sp_jumblewords(no_lines INT)
BEGIN
DROP TABLE IF EXISTS tmp_jumblewords;
CREATE TEMPORARY TABLE tmp_jumblewords (
`word` VARCHAR(340) NOT NULL);
REPEAT
INSERT INTO tmp_jumblewords
SELECT GROUP_CONCAT(f.word SEPARATOR ', ' )
FROM ( SELECT j.word AS word
FROM jumblewords j
ORDER BY RAND()
LIMIT 20) f;
SET no_lines = no_lines - 1;
UNTIL no_lines = 0
END REPEAT;
SELECT * FROM tmp_jumblewords;
END //
DELIMITER ;
CALL sp_jumblewords(20);