帮助加入和组

时间:2010-11-05 07:43:26

标签: php mysql

必须有一种方法,这样才能使用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 />';
   }
}

2 个答案:

答案 0 :(得分: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 :(得分:1)

select d.name, c.title from databases as d, categories as c where d.id=c.id_database;