MySQL - A query based on another query

∥☆過路亽.° 提交于 2021-02-17 02:06:15

问题


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";
            }
        }
    }
}

回答1:


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';



回答2:


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).




回答3:



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



来源:https://stackoverflow.com/questions/1935634/mysql-a-query-based-on-another-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!