加入3表问题

时间:2012-12-02 14:17:08

标签: php mysql sql count

我正在尝试解决这个问题:

“我们的数据: 我们在数据库中有三个Tabel:

Plant – describes the possible plants
Planted – whatever the gardener planted
Picked – the crop that was provided after the plantation."

我要做的是加入3个这样的表:

SELECT plant.PlantID, plant.name, planted.Seeds, picked.Amount
FROM plant 
INNER JOIN planted ON plant.PlantID = planted.PlantFK
INNER JOIN picked ON picked.PlantFK = plant.PlantID

因此,我可以获得有关特定PlantID的数据,种植了多少种子以及采摘了多少种子。 但由于某种原因,我得到了多个顽固性。 因为数据库有超过1个关于工厂的条目/选择了相同的PlantID ..

如何修复此加入?

1 个答案:

答案 0 :(得分:3)

只需使用汇总函数SUMCOUNTGROUP BY plant.PlantID, plant.name即可:

SELECT 
  plant.PlantID, 
  plant.name, 
  SUM(DISTINCT planted.Seeds) 'Planted', 
  SUM(DISTINCT picked.Amount) 'Picked' 
FROM plant 
INNER JOIN planted ON plant.PlantID = planted.PlantFK
INNER JOIN picked ON picked.PlantFK = plant.PlantID
GROUP BY   plant.PlantID, plant.name;

SQL Fiddle Demo

如果你想获得没有种子但从未挑选过的植物,你必须使用LEFT JOINIFNULL()来获得零而不是NULL这样:< / p>

SELECT 
  plant.PlantID, 
  plant.name, 
  SUM(IFNULL(DISTINCT planted.Seeds, 0)) 'Planted', 
  SUM(IFNULL(DISTINCT picked.Amount, 0)) 'Picked' 
FROM plant 
LEFT  JOIN planted ON plant.PlantID = planted.PlantID
LEFT  JOIN picked ON picked.PlantID = plant.PlantID
GROUP BY   plant.PlantID, plant.name;

Updated SQL Fiddle Demo