E
E
Erimax2022-03-05 09:17:08
SQL
Erimax, 2022-03-05 09:17:08

How to limit the number through join?

Hello.

There is a sql query sqlfiddle.com/#!9/773c4b/33 how to make each department have only 2 employees?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Michael, 2022-03-05
@Erimax

If MySQL is version 8, then he learned in window functions, so you can do this:

WITH tmp AS (SELECT department.name as department_name, employee.name, ROW_NUMBER() OVER (PARTITION BY department_id) AS rownum
FROM employee LEFT JOIN department
ON employee.department_id = department.id)
SELECT * FROM tmp
WHERE rownum <= 2

Complete example

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question