我写了很多类似下面的查询示例代码的查询。我想知道是否有更高效的代码/脚本?
$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";
}
}
}
}
答案 0 :(得分:9)
尝试使用SQL JOINs,如下例所示:
SELECT
*
FROM
table1
INNER JOIN
table2 ON (table2.table1ID = table1.ID)
WHERE
table1.date >= '2009-12-20';
答案 1 :(得分:1)
我不知道你的表的结构,但我修改了你的代码,以便它使用一个连接:
$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;
}
}
在这种情况下,您选择使用逗号分隔的多个表格,但您也可以使用INNER / OUTER / LEFT / RIGHT JOIN(请参阅第一个答案中的链接)。
答案 2 :(得分:-1)
您可以使用PDO
您的查询应该如下所示..
$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);