简体   繁体   English

加入3表问题

[英]Join with 3 tables issue

I am trying to solve this problem: 我试图解决这个问题:

"Our data: We have three Tabels in the database : “我们的数据:我们在数据库中有三个Tabel:

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

What I am trying to do is join to 3 tables like that: 我想要做的是加入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

So I could get data about specific PlantID how many seeds was planted and how many was picked. 因此,我可以获得有关特定PlantID的数据,种植了多少种子以及挑选了多少种子。 But for some reason Im getting multiple plantids. 但由于某种原因,我得到了多个顽固性。 Because the database has more then 1 entry about the plant/ picked about the same PlantID.. 因为数据库有超过1个关于工厂的条目/选择了相同的PlantID。

How can I fix that join? 我该如何修复加入?

Just use an aggregate function SUM or COUNT with a GROUP BY plant.PlantID, plant.name like so: 只需使用聚合函数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 SQL小提琴演示

If you want to get the plants that have no seeds, and never picked from, you have to use LEFT JOIN with IFNULL() to get zeros instead of NULL s like so: 如果你想获得没有种子的植物,并且从未挑选过,你必须使用LEFT JOINIFNULL()来获得零而不是NULL如下所示:

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 更新了SQL小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM