gareth
gareth

Reputation: 189

MySQL - A query based on another query

I write a lot of queries resembling the query example code below. I was wondering whether there was a more efficient code/script?

$query1 ="SELECT * FROM table1 WHERE date >= '$todaysdate' ";
$result1 = mysql_query($query1)
    or die ("Error in query: $query1. " . mysql_error());
if (mysql_num_rows($result1) > 0) {
    while($row1 = mysql_fetch_object($result1)) {

        echo "$row1-date";

        $query2 ="SELECT * FROM table2 WHERE table1ID >= '$row1-table1ID' ";
        $result2 = mysql_query($query2)
            or die ("Error in query: $query2. " . mysql_error());
        if (mysql_num_rows($result2) > 0) {
            while($row2 = mysql_fetch_object($result2)) {
                echo "$row->datatable2";
            }
        }
    }
}

Upvotes: 1

Views: 1913

Answers (3)

Daniel Vassallo
Daniel Vassallo

Reputation: 344281

Try using SQL JOINs, like the following example:

SELECT 
    * 
FROM 
    table1 
INNER JOIN 
    table2 ON (table2.table1ID = table1.ID)
WHERE 
    table1.date >= '2009-12-20';

Upvotes: 9

Alex
Alex

Reputation: 1


You can use PDO.
Your queries should look like this..

$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

$result = $sth->fetchAll(PDO::FETCH_COLUMN);
// OR
$result = $sth->fetchAll(PDO::FETCH_OBJ);
var_dump($result);

PDO MANUAL: http://php.net/manual/en/book.pdo.php

Upvotes: -1

Frank
Frank

Reputation: 406

I don't know about the structure of your tables, but I've modified your code so that it uses a join:

$query = 'SELECT table1.date, table2.datatable2 FROM table1, table2 WHERE table1.date >= \''.$todaysdate.'\' AND table2.table1ID >= table1.table1ID';
$result = mysql_query($query)
    or exit('Error in query: '.$query.' '.mysql_error());

if (mysql_num_rows($result) > 0)
{
    while($row = mysql_fetch_object($result))
    {
        echo $row->date;
        echo $row->datatable2;
    }
}

In this case you select multiple tables with FROM separated with commas, but you can also use INNER/OUTER/LEFT/RIGHT JOIN (see the link in the first answer).

Upvotes: 1

Related Questions