M
M
Maloy1232017-01-13 19:23:04
MySQL
Maloy123, 2017-01-13 19:23:04

How to select all in one query?

Hello! There is such a database structure:
content
|------
|id|title|content|user
|------
|1|Content Title 1|Content 1|1
|2|Content Title 2|Content 2|2
|3|Content Title 3|Content 3|1
categories
|------
|id|name
|------
|1|Category 1
|2|Category 2
|3|Category 3
|4|Category 4
|5|Category 5
content_categories
|------
|id|content_id|category_id
|------
|1|1|2
|2|1|3
|3|1|5
|4|2|1
|5|2|4
files
|------
|id|content_id|file_name|path
|------
|1|1|Photo.png|files/1/42/3332.png
|2|1|Photo.jpg|files/3/77/3532.jpg
|3|2|Document.doc|files/5/7388853 .doc
users
|------
|id|name
|------
|1|Paul
|2|Maria
3 queries in progress
Query 1

SELECT
  `c`.*, `u`.`name` AS `user_name`
FROM
  `content` AS `c`
  LEFT JOIN `users` AS `u` ON `u`.`id` = `c`.`user`
WHERE
  `c`.`id` = 1

Request 2
SELECT
  `c`.*
FROM
  `content_categories` AS `cc`
  LEFT JOIN `categories` AS `c` ON `c`.`id` = `cc`.`category_id`
WHERE
  `cc`.`content_id` = 1

Request 3
SELECT
  `id`, `file_name`, `path`
FROM
  `files`
WHERE
  `content_id` = 1

We get this result
Array
(
    [id] => 1
    [title] => Заголовок контента 1
    [content] => Контент 1
    [user] => 1
    [user_name] => Павел
    [categories] => Array
        (
            [0] => Array
                (
                    [id] => 2
                    [name] => Категория 2
                )

            [1] => Array
                (
                    [id] => 3
                    [name] => Категория 3
                )

            [2] => Array
                (
                    [id] => 5
                    [name] => Категория 5
                )

        )

    [files] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [file_name] => Фото.png
                    [path] => files/1/42/3332.png
                )

            [1] => Array
                (
                    [id] => 2
                    [file_name] => Фото.jpg
                    [path] => files/3/77/3532.jpg
                )
        )
)

Is it possible to combine these 3 queries to get the same result, or at least something like this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Grechushnikov, 2017-01-13
@maxyc_webber

it's not worth it. you save on matches. but for general development - LEFT JOIN learn

T
ThunderCat, 2017-01-13
@ThunderCat

Well, for starters, the query ALWAYS returns a "flat" array, there is no nesting, and secondly (although the first IMHO is enough) - the loss in calculating the multiplication of tables among themselves will be greater than the difference in the speed of individual samples + sorting in php.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question