0

I use MySQL & PHP and have the following database requests:

$result1 = mysql_query("SELECT nummer FROM abo WHERE usr = '{$usr}'");

while($row = mysql_fetch_object($result1))
{
  $sendung=$row->sendung;
  $result2 = mysql_query("SELECT *
                            FROM filme 
                           WHERE sendung = '{$sendung}' 
                        ORDER BY datum DESC LIMIT 0,1;");

  while($row = mysql_fetch_object($result2))
  {
    [...]
  }
}

For example there the second while is called 20 times -> there are 20 database request. But could I connect this request or optimize this requests?

One approach:

$arraysendung = array();

$result1 = mysql_query("SELECT nummer FROM abo WHERE usr = '{$usr}'");

while($row = mysql_fetch_object($result1))
{
  array_push($arraysendung,$row->sendung);
}

But how could I use $arraysendung in one request (is it possible)?

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
user1756209
  • 573
  • 10
  • 23

2 Answers2

2

Use a JOIN

SELECT nummer, filme.*
FROM abo
JOIN filme ON filme.sendung = abo.nummer
ORDER BY datum desc

This isn't a 100% replacement, since the LIMIT stuff isn't in place, but should be enough to get you started.

For the most part, anytime you're running two+ queries, and the later queries are based on results from of earlier queries, you can almost always rewrite them into a single JOINed query.

Marc B
  • 356,200
  • 43
  • 426
  • 500
1

The query:

SELECT filme.*
FROM filme JOIN 
    (SELECT sendung, max(datum) as datum FROM filme GROUP BY sendung) as md 
    ON filme.sendung = md.sendung AND md.datum = filme.datum
WHERE filme.sendung IN (SELECT nummer FROM abo WHERE  usr = '{$usr}')

should produce similar results, including the "LIMIT 1 part", provided "sendung,datum" is unique.

See: Subqueries, and JOIN

Sorin
  • 5,201
  • 2
  • 18
  • 45