0

这是我的代码,可以正常工作,但速度很慢:

    $graded = R::getAll("SELECT posts.id, posts.discussion, rating.rating, rating.itemid
                             FROM uv_forum_posts posts
                             JOIN uv_rating rating ON ( posts.id = rating.itemid )
                             WHERE posts.discussion = :discussion_id
                             GROUP BY posts.userid",
                             array(':discussion_id' => $discussion['id']));

    $total = R::getAll("SELECT posts.userid
                        FROM uv_forum_posts posts
                        WHERE posts.discussion = :discussion_id
                        GROUP BY userid",
                        array(':discussion_id' => $discussion['id']));

    $percentages[] = count($graded) / count($total) * 100;

$graded表示所有有评分的行。

$total代表所有用户参与,无论是否评分。

我只对结果集的数值感兴趣,我可以将这两个 MySQL 调用组合成一个返回两个数字的调用gradedtotal

4

2 回答 2

1

如果我正确理解您的要求,您可以尝试

SELECT p.userid,
       COUNT(*) total,
       COUNT(r.itemid) graded
  FROM uv_forum_posts p LEFT JOIN 
       uv_rating r ON p.id = r.itemid
 WHERE p.discussion = :discussion_id
 GROUP BY p.userid

输出:

| USERID | TOTAL | GRADED |
---------------------------
|      1 |     8 |      2 |
|      2 |     4 |      4 |

SQLFiddle

更新:如果您只想要所有帖子和用户的总计,那么

SELECT COUNT(*) total,
       COUNT(r.itemid) graded
  FROM uv_forum_posts p LEFT JOIN 
       uv_rating r ON p.id = r.itemid
 WHERE p.discussion = 1

输出:

| TOTAL | GRADED |
------------------
|    12 |      6 |

SQLFiddle

于 2013-05-07T05:04:16.427 回答
0

您可以简单地使用以下格式的查询:

Select
( SELECT posts.id, posts.discussion, rating.rating, rating.itemid
                             FROM uv_forum_posts posts
                             JOIN uv_rating rating ON ( posts.id = rating.itemid )
                             WHERE posts.discussion = :discussion_id
                             GROUP BY posts.userid,
                             array(':discussion_id' => $discussion['id']))) gradeCount,

(SELECT posts.userid
                        FROM uv_forum_posts posts
                        WHERE posts.discussion = :discussion_id
                        GROUP BY userid,
                        array(':discussion_id' => $discussion['id'])))totalCount
于 2013-05-07T04:53:22.853 回答