Question: I have two tables

The First table with Persons

```
person_id | person_name 

```

Second table is Books

```
book_id | person_id| book_name

```

The Books should be limited to 3 per person, and I want the result like this.

```
Person 1
Book 1
Book 2
Book 3

Person 2
Book 4
Book 5
Book 6

Person 3
Book 7
Book 8
Book 9

```

I'm using the following query

```
$load = "SELECT persons.person_id, persons.person_name, books.book_id, books.book_name, books.person_id, FROM persons LEFT JOIN books ON persons.person_id = books.persons_id";

```

But this gives a record for every book associated to each person, and adding a LIMIT will cause some people to not appear in the results. How can I LIMIT the results per person while still getting all people in the table?

Answer: 
The answer really depends on the RDBMS you use.

If you are using Postgres (or Oracle), you can use a window function to rank your results:

```sql
SELECT * FROM (
    SELECT
        persons.person_id, 
        persons.person_name, 
        books.book_id, 
        books.book_name, 
        books.person_id AS books_person_id,
        rank() OVER (PARTITION BY persons.person_id ORDER BY books.book_id) AS rank
    FROM persons
    INNER JOIN books ON persons.person_id = books.person_id
) AS foo
WHERE rank <= 3;

```

MySQL is missing window functions, so it is a bit more tricky. We will then use user defined variables:

```sql
SELECT * FROM (
    SELECT
        persons.person_id, 
        persons.person_name, 
        books.book_id, 
        books.book_name, 
        books.person_id AS books_person_id,
        CASE persons.person_id
            WHEN @prevVal THEN @curRank := @curRank + 1
            ELSE @curRank := 1 AND @prevVal := persons.person_id
        END AS rank
    FROM persons
    INNER JOIN books ON persons.person_id = books.person_id,
    (SELECT @curRank := 0, @prevVal := null) AS foo
    ORDER BY persons.person_id ASC
) AS bar WHERE rank <= 3;

```
Your question is not clear, but this may be all you need. Start with a simple query first.

```
SELECT book_name, book_id
FROM  books, persons
WHERE books.person_id = persons.person_id
ORDER by books.person_id

```