D
D
denism3002018-05-29 16:56:32
MySQL
denism300, 2018-05-29 16:56:32

How to optimize sql queries and get rid of the cycle?

I have a query like:

select a.field1, a.field2, a.field3, b.field1, b.field2
from table1 as a
left join table2 as b on a.field1 = b.field1
where ...

the data from it is written to the object.
Next, you need to add data to the object from other tables.
currently did this:
foreach $obj as o {
   select c.field1
   from table3 as c
   left join table4 as d on c.field2 = d.field2
   where c.field3 = a.field1
}

The code is somewhat exaggerated, but the meaning, I think, is clear.
it is clear that a bunch of calls to the database in a cycle loads the database
how to simplify it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
d-stream, 2018-05-29
@d-stream

What prevents you from expanding the original query with the necessary joins and getting exactly the right list?

A
Alexander Aksentiev, 2018-05-29
@Sanasol

From the result of the first query, select all a.field1 into the array.
Run the second query with a selection of all rows through where c.field3 in (array a.field1)
Total 2 queries
Or immediately join into one, what is the problem? (Depending on how many rows there should be in this cyclic query)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question