左连接&模棱两可的错误

时间:2018-06-14 15:02:48

标签: sql

我正在努力解决(最有可能)非常简单的问题。我一直收到以下错误:

Error: ambiguous column name: Rek.name

好的,我理论上知道这个错误意味着什么。但是,当我尝试使用它时,我不明白它出现的原因:

SELECT DISTINCT Rek.name AS abc, COUNT(DISTINCT Fav.FavId) AS def
FROM Rek, Fav
LEFT JOIN Artist ON Rek.RekId = Fav.RekId;

为什么Rek.name含糊不清?怎么能让它变得不模糊?

2 个答案:

答案 0 :(得分:2)

如果你想加入Fav表:

SELECT DISTINCT Rek.name AS abc, COUNT(DISTINCT Fav.FavId) AS def
FROM Rek
LEFT JOIN Fav ON Rek.RekId = Fav.RekId
GROUP BY Rek.name;

如果你还想要艺术家表:

SELECT DISTINCT Rek.name AS abc, COUNT(DISTINCT Fav.FavId) AS def
FROM Rek
LEFT JOIN Fav ON Rek.RekId = Fav.RekId
LEFT JOIN Artist ON Rek.common_attribute= Artist.common_attribute
GROUP BY Rek.name;

答案 1 :(得分:1)

咦?我认为你想要的查询是这样的:

SELECT Rek.name AS abc, COUNT(Fav.RekId) AS def
FROM Rek LEFT JOIN
     Fav
     ON Rek.RekId = Fav.RekId
GROUP BY Rek.name;

注意:

  • 不需要Artist表。
  • SELECT DISTINCT是一种执行GROUP BY的尴尬方式。
  • 据推测,fav.favid是主键。在这种情况下,您不需要COUNT(DISTINCT)