我的数据库中有2个表,并且需要以下PHP输出:
Dogs 5
Cats 2
Birds 4
我怎样才能做到这一点?
上面列出了类别,并列出了每个类别中有多少只狗,猫和鸟。
我在MySQL中有2个这样布置的表:
宠物(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
最佳答案
这是查询:
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 />';
}