环境为MySQL8.我有一张bird
号桌
+----+--------+--------+
| id | name | sex |
+----+--------+--------+
| 1 | bob | male |
| 2 | mary | female |
| 3 | jono | male |
+----+--------+--------+
鸟与Check
联系在一起
+----+-------------+---------+
| id | check_date | bird_id |
+----+-------------+---------+
| 1 | 2023-06-01 | 2 |
| 2 | 2023-07-01 | 2 |
| 3 | 2023-08-01 | 2 |
+----+-------------+---------+
每个check
可以有几个weights
个和measurements
个:
weights
个
+----+---------+----------+
| id | weight | check_id |
+----+---------+----------+
| 1 | 3.3 | 2 |
| 2 | 3.45 | 2 |
| 3 | 3.8 | 2 |
| 4 | 4.5 | 1 |
| 5 | 4.51 | 1 |
+----+---------+----------+
measurements
个
+----+---------+----------+
| id | measur | check_id |
+----+---------+----------+
| 1 | 95.2 | 1 |
| 2 | 97.4 | 1 |
| 3 | 96.4 | 1 |
| 4 | 99.1 | 3 |
| 5 | 98.1 | 3 |
+----+---------+----------+
对于给定的bird
,我如何返回包含以下内容的结果集
+---------+-----------+--------------+--------------------------+-------------------------+--------------------+-------------------+
| bird.id | bird.name | newest check | date newest measurements | avg newest measurements | date newest weight | avg newest weight |
+---------+-----------+--------------+--------------------------+-------------------------+--------------------+-------------------+
| 2 | mary | 2023-08-01 | 2023-08-01 | 98.6 | 2023-07-01 | 3.52 |
+---------+-----------+--------------+--------------------------+-------------------------+--------------------+-------------------+
我曾try 自己编写该查询,并取得了以下结果:
SELECT bird.id, bird.name, MAX(check.catch_date), weight
FROM bird
LEFT JOIN check ON bird.id=check.bird_id
LEFT JOIN measurements ON measurements.check_id=check.id
WHERE bird.id=2
GROUP BY id, weight;
But the way to nest and average the result of measurements
个 and length
which could be associated to different checks is where I am stuck so narrative on how the answer SQL works would be helpful.