帮助加入查询

时间:2009-09-22 00:30:27

标签: sql mysql

SELECT game_ratingstblx245v.game_id,avg( game_ratingstblx245v.rating ) 
         as avg_rating,
       count(DISTINCT game_ratingstblx245v.userid) 
          as count,
       game_data.name,
       game_data.id ,
       avg(game_ratings.critic_rating),count(DISTINCT game_ratings.critic) 
         as cr_count
FROM game_data 
LEFT JOIN game_ratingstblx245v ON game_ratingstblx245v.game_id = game_data.id 
LEFT JOIN game_ratings         ON game_ratings.game_id = game_data.id 
WHERE game_data.release_date < NOW() 
GROUP BY game_ratingstblx245v.game_id 
ORDER BY game_data.release_date DESC,
         game_data.name


我目前正在使用此查询从3个表中提取值
game_data - id(外键),name,release_date \ games info
game_ratings - game_id(外键),评论家,评级\评论评级
game_ratingstblx245v - game_id(外键),评级,用户ID \用户评分


我想用这个查询做的是通过release_date降序从表game_data中选择所有id,然后检查表game_ratings和game_ratingsblx245v的avg等级,对应于个人id(如果游戏没有被评级为结果)应该从后两个表的字段中返回null)..现在我面临的问题是结果没有按预期出现(一些未评级的游戏正在出现而其他游戏没有出现),你们可以查一下吗?我的询问并告诉我,如果是的话,我错了...谢谢

1 个答案:

答案 0 :(得分:2)

您不应该在GROUP BY中使用game_ratingstblx245v.game_id列,因为当给定游戏ID没有评级时它可能为NULL。请改用game_data.id

以下是我编写查询的方法:

SELECT g.id, g.name,
       AVG( x.rating ) AS avg_user_rating,
       COUNT( DISTINCT x.userid ) AS user_count,
       AVG( r.critic_rating ) AS avg_critic_rating, 
       COUNT( DISTINCT r.critic ) AS critic_count
FROM game_data g
LEFT JOIN game_ratingstblx245v x ON (x.game_id = g.id)
LEFT JOIN game_ratings r         ON (r.game_id = g.id)
WHERE g.release_date < NOW() 
GROUP BY g.id 
ORDER BY g.release_date DESC, g.name;

请注意,虽然此查询会在xr之间生成笛卡尔积,但它不会影响平均评分的计算。请注意,如果您正在进行SUM()COUNT(),那么计算可能会被意外的笛卡尔积夸大。