MySQL: Select Random Entry, But Weight Towards Certain Entries

MySQL select random row that has a count of 3

You can subselect the words with count(*) bigger than 2 and then pick a random selection
in the outer query

Schema (MySQL v8.0)

CREATE TABLE wordtable (
`word` VARCHAR(5),
`wordType` VARCHAR(4)
);

INSERT INTO wordtable
(`word`, `wordType`)
VALUES
('house', 'noun'),
('house', 'noun'),
('house', 'noun'),
('car', 'noun'),
('car', 'noun'),
('car', 'noun'),
('floor', 'noun'),
('floor', 'noun');

Query #1

SELECT 
`word`
FROM wordtable
WHERE `word` in (
SELECT
`word`
FROM wordtable
WHERE `wordType` = 'noun'
GROUP BY `word`
HAVING count(`word`) >= 3)
ORDER BY RAND()
LIMIT 3;


Leave a reply



Submit