如何在JOIN语句中指定WHERE?

时间:2012-02-11 05:16:27

标签: php mysql join

这是我第一次尝试使用JOIN MySQL语句......

我有2张表.. gamesgames_ratings

两个表都有一个id列。 id代表游戏的id。而我只想得到评级栏中的平均值,其中games_ratings中的id等于游戏表中的id。

SELECT a.id, a.name, AVG(b.rating) AS average FROM games a LEFT JOIN games_ratings b GROUP BY a.id ORDER BY average DESC LIMIT 50;

任何想法?

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT a.id, a.name, AVG(b.rating) AS average 
    FROM games a 
    LEFT JOIN games_ratings b
    ON a.id = b.id # <-- You need this line I believe 
GROUP BY a.id
ORDER BY average DESC LIMIT 50;

编辑:如果没有完整的架构,这有点难,但您可以尝试这样的事情。

SELECT a.id, a.name, AVG(b.rating) AS average, COUNT( b.id) as votes
    FROM games a 
    LEFT JOIN games_ratings b
    ON a.id = b.id 
GROUP BY a.id
ORDER BY votes DESC, average DESC LIMIT 50; # <-- You may need to modify this line

答案 1 :(得分:1)

不要忘记他要求的WHERE条款:

  

其中games_ratings中的id等于游戏表中的id

> SELECT a.id, a.name, AVG(b.rating) AS average 
>     FROM games a 
>     LEFT JOIN games_ratings b
>     ON a.id = b.id # <-- You need this line I believe
>     **WHERE a.id = b.id**  
>     GROUP BY a.id 
>     ORDER BY average DESC LIMIT 50;