0

我已经让自己对平均和加入表格有点恼火。

本质上,我想使用 Highcharts 显示不同植物物种的平均高度,从 MySQL 数据库中提取数据。不幸的是,高度数据和物种名称被设置为添加到不同的表格中。

我已经让它工作了,但是当我下载数据并在 Excel 中找到平均值时,这些数字与显示的数字不同 - 所以我显然做得不对。我已经仔细检查过我在 Excel 中做对了,所以几乎可以肯定是我的 MySQL 查询填满了。

实际表格中有很多条目,所以我只是在下面放了一个例子。

我目前的查询是:

<?php
$result = mysql_query("
SELECT DISTINCT(plant_records.plant_id), ROUND(AVG(plant_records.height),2) as plant_average, plant_list.id, plant_list.plant_species
FROM plant_records
INNER JOIN plant_list
ON plant_records.plant_id=plant_list.id
GROUP BY plant_list.plant_species
")  or die(mysql_error()); 

while ($row = mysql_fetch_array($result)) {
$xAxisValues[] = "'" . $row['plant_species'] . "'";
$AseriesValues[] = $row['plant_average'];
}
?>

我做对了吗?我找到了一些很好的教程来解释连接,比如这个,但我仍然很困惑。我想知道我在加入他们之前是否在平均水平,还是什么?

Records 表中的“plant_id”对应于 List 表中的“id”

植物记录:

id  plant_id    date_recorded   height
1   3           01/01/2013      0.2523123
2   1           02/01/2013      0.123
3   3           03/02/2013      0.446
4   3           04/03/2013      0.52
5   1           05/03/2013      0.3
6   2           06/03/2013      0.111
7   2           07/05/2013      0.30
8   4           08/05/2013      0.22564
9   1           09/05/2013      1.27
10  3           10/05/2013      1.8

植物列表:

id  registration_date   contact_name    plant_species   plant_parent
1   01/01/2013          Dave            ilex_prinos     London_Holly
2   02/01/2013          Bill            acer_saccharum  Brighton_Maple
3   01/01/2013          Bob             ilex_prinos     London_Holly
4   04/01/2013          Bruno           junip_communis  Park_Juniper

编辑: 我已经尝试过使用 Excel 查找数据的所有可能方法(例如,故意不过滤唯一 ID、不同的平均类型、选择多个物种等)来查找我的查询正在使用的计算,但我无法得到相同的结果结果。

4

2 回答 2

0

如果我们假设这plant_id不是唯一标识符 - 这意味着单个plant_id仅适用于任何给定物种的单个植物,并且您想知道单个物种的平均高度是多少,您可以这样做:

SELECT PL.plant_species, ROUND(AVG(PR.height),2) as plant_average
FROM plant_records AS PR
JOIN plant_list AS PL
     ON PR.plant_id=PL.id
GROUP BY PL.plant_species

这将返回如下内容:

plant_species   plant_average
acer_saccharum  0.2100000
ilex_prinos     0.6700000
junip_communis  0.2300000
于 2013-11-13T13:08:10.260 回答
0

我注意到您的查询目前存在两个问题。

  1. 选择plant_list.id同时拥有 aGROUP BY plant_list.plant_species不会产生任何感兴趣的结果,因为 MySQL 将从id与每个物种匹配的任何植物中返回任意值。

  2. 您声明您只对最近的录音感兴趣,但您的查询中没有任何内容反映这一事实。

鉴于该信息,请尝试以下查询:

SELECT ROUND(AVG(pr.height),2) as plant_average, plant_list.plant_species
FROM plant_records pr
INNER JOIN plant_list
ON pr.plant_id=plant_list.id
WHERE pr.date_recorded = (
    SELECT MAX(pri.date_recorded) FROM plant_records pri
    WHERE pri.plant_id = pr.plant_id
)
GROUP BY plant_list.plant_species

或者,如果您只需要特定日期的平均高度,只需将其直接传递到查询中,而不是使用子查询。

于 2013-11-13T13:14:43.353 回答