mySQL查询语法 - 多个表和连接

时间:2014-09-04 16:09:28

标签: mysql sql

我目前有以下表格:

小屋

LodgeID (PK)
Lodge
etc

分数

ScoreID (PK)
Score
CategoryID (FK)
LodgeID (FK)

(也用于计算ScoreCount和AverageScore)

categoriesFull

CategoryID (PK)
Category

国家

CountryID (PK)
Country

提名

NominationID (PK)
LodgeID (FK)
CategoriesFullID (FK) (--to categoriesFull.CategoryID)
SW_finalist
SW_rank

所以,如果我有以下内容:

小屋

LodgeID, Lodge
798, Borana Lodge

分数

ScoreID, LodgeID, CategoryID, Score
1001, 798, 7, 3
1002, 798, 7, 6
1003, 798, 7, 9

categoriesFull

CategoryID 
7

国家

CountryID
3

提名

NominationID, LodgeID, CategoryID, SW_finalist, SW_rank
1234, 798, 7, Yes, 2

我希望能够输出

LodgeID, Lodge, CategoryID, CountryID, ScoreCount, AverageScore, NominationID, SW_finalist, SW_rank
798, Borana Lodge, 7, 3, 3, 6, 1234, Yes, 2

这是我在介绍提名表之前所拥有的:

SELECT 
   ScoreID, COUNT(ScoreID) as scoreCount, AVG(Score) as AverageScore, lodges.LodgeID, 
   Lodge, Country, lodges.CountryID, CategoryID, SW_finalist, SW_rank 
FROM 
   lodges 
INNER JOIN 
   countries ON lodges.CountryID = countries.CountryID 
INNER JOIN 
   nominations ON lodges.LodgeID = nominations.LodgeID 
INNER JOIN 
   scores ON lodges.LodgeID = scores.LodgeID 
WHERE 
   lodges.CountryID = 3  
   AND CategoryID = '7' 
GROUP BY 
   Lodge

这似乎有助于输出:

LodgeID, Lodge, CategoryID, CountryID, ScoreCount, AverageScore
798, Borana Lodge, 7, 3, 3, 6

我只需要在提名表中标记这三个字段。我认为提名的加入也需要在categoriesFull.CategoryID上,但是当我尝试类似

的时候
SELECT 
   ScoreID, COUNT(ScoreID) as scoreCount, AVG(Score) as AverageScore, lodges.LodgeID, 
   Lodge, Country, lodges.CountryID, CategoryID, SW_finalist, SW_rank 
FROM 
   lodges 
INNER JOIN 
   countries ON lodges.CountryID = countries.CountryID 
LEFT OUTER JOIN 
   nominations ON lodges.LodgeID = nominations.LodgeID AND nominations.CategoriesFullID = categoriesFull.CategoryID 
INNER JOIN 
   scores ON lodges.LodgeID = scores.LodgeID 
WHERE 
   lodges.CountryID = 3 
   AND CategoryID = '7' 
GROUP BY 
   Lodge

我收到有关categoriesFull.CategoryID是未知列的错误。

我认为所有的表都有他们需要的ID,但是非常感谢任何有关正确联接以使其工作的帮助。

实际上,它看起来并没有起作用 - 我看起来像是这样的查询:

SELECT ScoreID, COUNT(ScoreID) as scoreCount, AVG(Score) as AverageScore, lodges.LodgeID,       lodges.Lodge, Country, lodges.CountryID, categoriesFull.CategoryID, nominations.NominationID,     SW_finalist, SW_rank, 2015_Awards_Participant FROM lodges 
INNER JOIN countries ON lodges.CountryID = countries.CountryID 
INNER JOIN scores ON lodges.LodgeID = scores.LodgeID 
INNER JOIN nominations ON lodges.LodgeID=nominations.LodgeID 
INNER JOIN categoriesFull ON nominations.CategoriesFullID = categoriesFull.CategoryID AND     scores.categoryID = categoriesFull.CategoryID
WHERE lodges.CountryID = 3 AND scores.CategoryID=7 GROUP BY Lodge

但看起来它正在对ScoreID进行多次计算 - 如果Lodge在提名表中有3项提名,则得分数乘以3。

0 个答案:

没有答案