需要双表SQL查询帮助

时间:2016-06-02 15:39:21

标签: mysql

我收到两张包含以下数据的表格:

动物表:
Registration_Number


PEDIGREE TABLE:
Ped_Registration_Number
名称
Sire_Number

我需要写一个sql语句,告诉我公牛的名字,公牛犊的数量以及他产犊的小母牛的数量。

我不知道从哪里开始,或者甚至可以通过表格设置来完成。

'性别'列中的任何一个都是' B'对于Bull或者' H'为小母牛。 Sire_Number告诉我们动物的陛下(公牛)是谁。 Sire_Number和Registartion_Number将相关。

2 个答案:

答案 0 :(得分:1)

您可以从此查询开始:

SELECT p.Name
FROM pedigree p
INNER JOIN animal a
ON a.Registration_Number = p.Ped_Registration_Number
  AND a.Sex = 'B'

将返回所有公牛的名字。

这是小母牛犊的数量部分:

SELECT p.Name,
  COUNT(DISTINCT calves.Ped_Registration_Number) calves_number
FROM pedigree p
INNER JOIN animal a
ON a.Registration_Number = p.Ped_Registration_Number
  AND a.Sex = 'B'
LEFT JOIN pedigree calves
  ON p.Ped_Registration_Number = calves.Sire_Number
GROUP BY p.Ped_Registration_Number

最后一种方法:

SELECT p.Name,
  SUM(IF(h_b.sex='B',1,0)) calves_b,
  SUM(IF(h_b.sex='H',1,0)) calves_h,
FROM pedigree p
INNER JOIN animal a
ON a.Registration_Number = p.Ped_Registration_Number
  AND a.Sex = 'B'
LEFT JOIN pedigree calves
  ON p.Ped_Registration_Number = calves.Sire_Number
LEFT JOIN a h_b
  ON calves.Ped_Registration_Number = h_b.Registration_Number
GROUP BY p.Ped_Registration_Number

答案 1 :(得分:0)

SELECT p.Name,
SUM(IF(h_b.sex='B',1,0)) calves_b,
SUM(IF(h_b.sex='H',1,0)) calves_h,
FROM pedigree p
INNER JOIN animal a
ON a.Registration_Number = p.Ped_Registration_Number
AND a.Sex = 'B'
LEFT JOIN pedigree calves
ON p.Ped_Registration_Number = calves.Sire_Number
LEFT JOIN a h_b
ON calves.Ped_Registration_Number = h_b.Registration_Number
GROUP BY p.Ped_Registration_Number