2010-11-05 94 views
1

必須有一種方法才能使用1個查詢。我使用的是加入和一組由幫助加入並加入羣組

這裏是我當前的代碼假設:

$sql = mysql_query("select * from `databases` where `id` in (select `id_database` from `categories`)"); 

while ($row = mysql_fetch_assoc($sql)) 
{ 
    echo $row['name'] . '<br />'; 

    $sql_c = mysql_query("select * from `categories` where `id_database`='" . $row['id'] . "'"); 

    while ($row_c = mysql_fetch_assoc($sql_c)) 
    { 
     echo $row_c['title'] . '<br />'; 
    } 
} 

回答

1

有......這樣的事情應該做的伎倆。

$sql = mysql_query("select * from databases db JOIN categories cat on (db.id=cat.id_database) ORDER BY db.name"); 

$last_name = null; 
while ($row = mysql_fetch_assoc($sql)) 
{ 
    if($row['db.name'] !== $previous_name) { 
     echo $row['db.name'] . '<br />'; 
     $previous_name = $row['db.name']; 
    } 
    echo $row['cat.title'] . '<br />'; 
} 
1
select d.name, c.title from databases as d, categories as c where d.id=c.id_database; 
+0

唯一的事情是我需要呼應數據庫'name',然後在該數據庫中的'categories'列表... – kevin 2010-11-05 13:07:39

+0

所以只是遍歷結果集和呼應的名稱只有當數據庫與之前的數據庫不同時才能訪問數據庫。就像李建議的那樣...... – mitch 2010-11-05 23:19:34