A
A
Alexander2021-11-04 20:49:12
MySQL
Alexander, 2021-11-04 20:49:12

How to make MySql select from multiple tables?

Hello.

There is such a scheme of tables:
618413c76a805628452107.png

Need:
Make a query in such a way as to select all records from the Resources table with values ​​from the Variable_values ​​table.

The result should look something like this:

resource
----id
----title
----variables
--------variable
------------id
------------title
------------values
----------------value
----------------value
----------------value
--------variable
------------id
------------title
------------values
----------------value
----------------value
----------------value
--------variable
------------id
------------title
------------values
----------------value
----------------value
----------------value
----childs
--------resource
------------id
------------title
------------variables
----------------variable
--------------------id
--------------------title
--------------------values
------------------------value
------------------------value
------------------------value
------------childs
и т.д.


The Resources table is tree-like. Depth is not limited. But for my task, I need to select all posts that have the following conditions and nesting:
Post with template Model
---- Post with template Design model
-------- Post with template Design Series

That is, nesting depth 3. template id's are known from the start.

I can handle this task like this:
SELECT * FROM Resources AS Models
LEFT JOIN Resources AS Designs ON Designs.parent_id = Models.id
LEFT JOIN Resources AS Batches ON Batches.parent_id = Designs.id
WHERE Designs.template_id = id шаблона дизайна модели
AND WHERE Batches.template_id = id шаблона серии дизайна


But then I don’t understand how to attach variables (Variables) and their values ​​​​(Variable_values). Joining is very costly in terms of query execution time.

I would like to have only one request, since it is necessary to use LIMIT for the selection, as well as different conditions for the selection (Where).

Please let me know what options you see.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
AUser0, 2021-11-04
@AUser0

SELECT * FROM Resources AS Models
LEFT JOIN Resources AS Designs ON (Designs.parent_id = Models.id AND Designs.template_id = id шаблона дизайна модели)
LEFT JOIN Resources AS Batches ON (Batches.parent_id = Designs.id AND Batches.template_id = id шаблона серии дизайна)
WHERE Models.parent_id IS NULL
AND Designs.id IS NOT NULL
AND Batches.id IS NOT NULL

Now stick JOINs from variables to this query.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question