MySQL连接 - 循环遍历所有类别和输出项

时间:2014-02-09 13:11:57

标签: php mysql sql join

我的桌子:

分类

id (int)
name (varchar)

产品:

id (int)
name (varchar)
category (int)

是否可以使用输出这样的数据:

Category1
---------
Item1
Item2

Category2
---------
Item3
Item4

使用JOIN?我能够这样做:

$query = mysql_query("SELECT id, name FROM categories");

while ($row = mysql_fetch_assoc($query))
{
    echo $row["name"];

    $query2 = mysql_query("SELECT * FROM dishes WHERE category = {$row["id"]}");

    while ($row2 = mysql_fetch_assoc($query2))
    {
        echo ...
    }
}

然而,正如您可能知道的那样,这是一种可怕的方法,而且永远不应该这样做。

2 个答案:

答案 0 :(得分:1)

确实,使用JOIN,然后按类别排序。在PHP内部,您只需检查类别是否已更改为下一个,如果是,则显示一个漂亮的表标题(代码待定)

$q = mysql_query("SELECT dishes.id, dishes.name, categories.name as catname, categories.id as catid FROM dishes LEFT JOIN categories ON (dishes.category=categories.id) ORDER BY categories.name ASC");

$currCat = 0;
while($dish = mysql_fetch_array($q)) {
   if($currCat != $dish['catid']) {
      echo 'Category: ' . $dish['catname'];
      $currCat = $dish['catid'];
   }
   echo $dish['name'];
}

mysql_free_result($q);

在旁注中,你真的不应该再使用mysql扩展了。它已被弃用。相反,您应该使用MySQLi或PDO扩展。

答案 1 :(得分:1)

$SQL = "SELECT c.name, d.*
        FROM categories AS c
        JOIN dishes AS d ON ( d.category = c.id ) 
        ORDER BY c.name ASC";

$result = mysql_query($SQL) or die (mysql_error());

$oldCategory = null;

while ($row = mysql_fetch_assoc($result))
{
    if( $oldCategory != $row["name"] )
    {
         echo $row["name"]; 

         $oldCategory = $row["name"];
    }

    print_r( $row );
}

mysql_free_result($result);

NB 不推荐使用mysql_ * ...使用mysqli_ *或pdo!