A
A
Art. Ku.2016-06-29 18:05:59
PHP
Art. Ku., 2016-06-29 18:05:59

Does the load on the database increase if you nest one query in another?

I have around this:

$z = 0;
$a= mysql_query("SELECT h 
        FROM b
       ");
while ($c=mysql_fetch_array($a))
{
       if ($z >10) break;
       $d= mysql_query("SELECT g 
        FROM e
        WHERE h = $c[h]
       ");
        while ($f=mysql_fetch_array($d))
        {
            echo $f['g'];
            $z++;
        }
}

Does such nesting affect the speed and load, or is it better to drive the first output into an array, and put the second one into the foreach loop? Thank you.
UPD. There is no task to merge two databases. The first query is needed exclusively for the WHERE of the second. Everything is complicated there, the example is simplified for understanding.
UPD 2 The
example above or the example below, which is better?
$m= array();
$z = 0;
$a= mysql_query("SELECT h 
        FROM b
       ");
while ($c=mysql_fetch_array($a))
{ 
       array_push($m, "$c[h]"); 
}
foreach ( $m as $mo ) {

       if ($z >10) break;
       $d= mysql_query("SELECT g 
        FROM e
        WHERE h = $mo[h]
       ");
        while ($f=mysql_fetch_array($d))
        {
            echo $f['g'];
            $z++;
        }
}
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry Belyaev, 2016-06-29
@bingo347

Your task is solved with one query:

SELECT g FROM e
INNER JOIN b ON b.h = e.h

A lot of requests is always an extra load + performance dips

D
Dimonchik, 2016-06-29
@dimonchik2013

https://habrahabr.ru/post/31129/
everything is not so simple/unambiguous there, look at Mail ru lectures on Muskul and Aksenov's lectures (author of Sphinxsearch), there is no universal recipe for comparable tasks - and joins are not so resource-intensive, and muscle he can choose a non-optimal path himself (hence the indication of specific indexes), etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question