Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do equivalent of "limit distinct"?

Tags:

sql

mysql

How can I limit a result set to n distinct values of a given column(s), where the actual number of rows may be higher?

Input table:

client_id, employer_id, other_value
1, 2, abc
1, 3, defg
2, 3, dkfjh
3, 1, ldkfjkj
4, 4, dlkfjk
4, 5, 342
4, 6, dkj
5, 1, dlkfj
6, 1, 34kjf
7, 7, 34kjf
8, 6, lkjkj
8, 7, 23kj

desired output, where limit distinct=5 distinct values of client_id:

1, 2, abc
1, 3, defg
2, 3, dkfjh
3, 1, ldkfjkj
4, 4, dlkfjk
4, 5, 342
4, 6, dkj
5, 1, dlkfj

Platform this is intended for is MySQL.

like image 478
ʞɔıu Avatar asked Dec 14 '22 05:12

ʞɔıu


1 Answers

You can use a subselect

select * from table where client_id in 
(select distinct client_id from table order by client_id limit 5)
like image 61
Vinko Vrsalovic Avatar answered Dec 18 '22 00:12

Vinko Vrsalovic