PHP输出摘要基于2个表。

时间:2011-07-29 02:01:07

标签: php mysql

我的数据库中有2个表,我想要以下的PHP输出:

Dogs 5   
Cats 2  
Birds 4  

我该怎么做?

上面列出了每个类别中狗,猫和鸟的数量的类别。

我在MySQL中有两个表格,如下所示:

宠物(MySql表名)

AnimalNAME | AnimalCAT | AnimalDES  
   Bolt    |      1    | Smelly dog  
   Minx    |      2    | Snobby cat  
   Twit    |      3    | Cherpy bird  
   Rony    |      1    | Sneaky dog

类别(MySql表名)

AnimalCAT | Name 
    1     | Dogs  
    2     | Cats  
    3     | Birds

1 个答案:

答案 0 :(得分:1)

以下是查询:

SELECT
  Categories.Name,
  COUNT(Pets.AnimalCAT)
FROM
  Categories
LEFT OUTER JOIN
  Pets
ON
  Categories.AnimalCAT = Pets.AnimalCAT
GROUP BY
  Categories.AnimalCAT

PHP示例:

mysql_connect('localhost', 'username', 'password');
mysql_select_db('dbname');

$sql = "
    SELECT
      Categories.Name AS `category`,
      COUNT(Pets.AnimalCAT) AS `count`
    FROM
      Categories
    LEFT OUTER JOIN
      Pets
    ON
      Categories.AnimalCAT = Pets.AnimalCAT
    GROUP BY
      Categories.AnimalCAT
";
$result = mysql_query($sql) or die("Error in SQL: " . mysql_error());

while ($row = mysql_fetch_array($result)) {
  echo $row['category'] . ' ' . $row['count'] . '<br />';
}