Skip to content

Instantly share code, notes, and snippets.

CREATE TABLE `names` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`group_id` int(10) unsigned NOT NULL,
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1;
CREATE TABLE `groups` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
@ozgurky
ozgurky / random_rows_from_groups.sql
Last active August 24, 2019 06:57
How to get random n rows per each group using MySQL
select id, name, group_id from
(
select
id,
name,
group_id,
@group_rank := IF(@current_group=group_id, @group_rank + 1, 1) as group_rank,
@current_group := group_id
from (
select id, name, group_id, CONCAT(group_id, '-', round(rand() * 100)) as rand_rank