H
H
happ2016-08-05 18:14:29
MySQL
happ, 2016-08-05 18:14:29

How to select posts and tags from DB?

For example, a selection of 10 posts, each post can have an arbitrary number of tags, for example 5. How to make a selection correctly? how to do it in this case, with one request or make additional requests when iterating over an array from the database?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Entelis, 2016-08-05
@happ

I really like to ask this question at interviews)
The correct answer in my opinion is: depending on the workload.
1. The obvious quick solution - stupidly 3NF in the database, 1 request to get a list of posts, 1-2 more requests to get all the tags from all these posts, merge arrays in PL.
2. As the load appears, you can deal with various denormalizations (at least you can store tag id in a denormalized way, as a maximum, tag texts too).

E
entermix, 2016-08-05
@entermix

Make an additional request
UPD:
Something like this:

$posts = $sql->get("SELECT `id`, `name` FROM `posts` WHERE 1");

foreach ($posts as $post) {
    echo $post->name;

    $tags = $sql->get("SELECT `id`, `name` FROM `post_tags` WHERE `post_id` = $post->id");

    foreach ($tags as $tag) {
        echo $tag->name;
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question