了解MySQL的回归

时间:2016-05-06 11:21:03

标签: mysql

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个家庭。为什么只返回一个?

2 个答案:

答案 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;