MySQL查询是:
SELECT orders.scientific_name AS 'Order',
families.scientific_name AS 'Family',
COUNT(*) AS 'Number of Birds'
FROM birds, bird_families AS families, bird_orders AS orders
WHERE birds.family_id = families.family_id
AND families.order_id = orders.order_id
AND orders.scientific_name = 'Pelecaniformes';
输出是:
+----------------+-------------+-----------------+
| Order | Family | Number of Birds |
+----------------+-------------+-----------------+
| Pelecaniformes | Pelecanidae | 224 |
+----------------+-------------+-----------------++
但我在数据库中有5个家庭。为什么只返回一个?
答案 0 :(得分:1)
您正在使用COUNT(*)
将其转换为聚合查询。如果没有GROUP BY
,则只返回一行。
我建议您开始使用:
COUNT(*)
。JOIN
语法替换逗号。然后努力寻找你真正想写的查询。所以,开始吧:
SELECT o.scientific_name AS `Order`,
bf.scientific_name AS Family
FROM birds b JOIN
bird_families bf
ON b.family_id = bf.family_id JOIN
bird_orders bo
ON bf.order_id = o.order_id
WHERE o.scientific_name = 'Pelecaniformes';
此时,您可以添加COUNT(*)
和GROUP BY o.scientific_name, bf.scientific_name
。
答案 1 :(得分:0)
如果orders.scientific_name ='Pelecaniformes'
中有5个家庭然后你应该使用group by
SELECT orders.scientific_name AS 'Order',
families.scientific_name AS 'Family',
COUNT(*) AS 'Number of Birds'
FROM birds, bird_families AS families, bird_orders AS orders
WHERE birds.family_id = families.family_id
AND families.order_id = orders.order_id
AND orders.scientific_name = 'Pelecaniformes'
Group by orders.scientific_name , families.scientific;