我有一个包含4列的表,如下所示:
ID - username - rating - solved
数据库适用于拼图网站。 ID
是拼图的#,username
字段是解决它的用户,solved
是布尔值,如果用户已经解决了它。在主页面上,我列出了谜题。我得到了谜题的数据(来自另一张表),登录用户的谜题的解决值,但是当我尝试获得平均评级时,它平均一个值,即登录用户对谜题的评级,并忽略了拼图的任何其他评级。这可以在一个查询中完成,还是只有两个,一个单独的查询?怎么样?
哦,如果没有用户登录,这意味着我不必从评级表中获取solved
值,评级是平均的,一切正常。
编辑:这是代码。 $ logged是用户登录的,因此前两个查询有效,而后两个查询没有。
if ($logged) {
$query_recent = "SELECT id, owner, title, hidden, x, y, solved, points, AVG(rating) AS average FROM `users`, `cwords` LEFT JOIN `ratings` ON `cwords`.`id`=`ratings`.`cw_id` AND `ratings`.`owner_id` = '$username' WHERE `cwords`.`public` = 1 AND `owner` = `username` GROUP BY `id` ORDER BY `id` DESC LIMIT $from, 30";
$query_top = "SELECT id, owner, title, hidden, x, y, solved, points, AVG(rating) AS average FROM `users`, `cwords` LEFT JOIN `ratings` ON `cwords`.`id`=`ratings`.`cw_id` AND `ratings`.`owner_id` = '$username' WHERE `cwords`.`public` = 1 AND `owner` = `username` GROUP BY `id` ORDER BY average DESC LIMIT $from, 30";
} else {
$query_recent = "SELECT id, owner, title, hidden, x, y, points, AVG(rating) AS average FROM `users`, `cwords` LEFT JOIN `ratings` ON `cwords`.`id`=`ratings`.`cw_id` WHERE `cwords`.`public` = 1 AND `owner` = `username` GROUP BY `id` ORDER BY `id` DESC LIMIT $from, 30";
$query_top = "SELECT id, owner, title, hidden, x, y, points, AVG(rating) AS average FROM `users`, `cwords` LEFT JOIN `ratings` ON `cwords`.`id`=`ratings`.`cw_id` WHERE `cwords`.`public` = 1 AND `owner` = `username` GROUP BY `id` ORDER BY average DESC LIMIT $from, 30";
};
编辑2:我尝试了2次查询,但是如果我尝试在另一个中选择solved
值,我无法通过AVG(rating)
订购,我又回到原来的问题。有什么帮助吗?
$query_top_solved = "SELECT id, solved FROM cwords LEFT JOIN ratings ON `cwords`.`id`=`ratings`.`cw_id` AND `ratings`.`owner_id` = '$username' WHERE `cwords`.`public` = 1 GROUP BY cw_id ORDER BY AVG(rating) DESC LIMIT $from, 30";
按当前登录用户的评分单一订购。
答案 0 :(得分:1)
您需要两个单独的查询。一个用于获取用户的分数,另一个用于获取总体平均分数。
SELECT rating, solved
FROM ...
WHERE username=$userID AND ID=$puzzleID
和
SELECT AVG(rating), AVG(solved)
FROM ...
WHERE ID=$puzzleID