help with a join and group
There's got to be a way so that this only uses 1 query. I'm assuming using a join and a group by
Here's my current code:
$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 />';
}
}
There is... something like this should do the trick.
$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 />';
}
select d.name, c.title from databases as d, categories as c where d.id=c.id_database;
精彩评论