0
LEFT JOIN
(
    SELECT user_id, review, COUNT(user_id) totalCount
    FROM reviews
    GROUP BY user_id
) b ON b.user_id= b.user_id 

我试图WHERE LENGTH(review) > 100在某个地方适应它,但每次我放它,它都会给我带来问题。

上面的子查询将所有评论总数按user_id. 我只是想再增加一个资格。仅计算长度超过 100 条的评论。

在旁注中,我已经看到了这个功能CHAR_LENGTH——不确定这是否是我需要的。

编辑:

这是完整的查询,可以满足我的需求:

    static public $top_users = "
            SELECT  u.username, u.score,
            (COALESCE(a.totalCount, 0) * 4) +
            (COALESCE(b.totalCount, 0) * 5) +
            (COALESCE(c.totalCount, 0) * 1)  +
            (COALESCE(d.totalCount, 0) * 2)  +
            (COALESCE(u.friend_points, 0)) AS totalScore
            FROM users u 
            LEFT JOIN
                (
                    SELECT user_id, COUNT(user_id) totalCount
                    FROM items 
                    GROUP BY user_id
                ) a ON a.user_id= u.user_id
            LEFT JOIN
                (
                    SELECT user_id, COUNT(user_id) totalCount
                    FROM reviews
                    GROUP BY user_id
                ) b ON b.user_id= u.user_id
            LEFT JOIN
                (
                    SELECT user_id, COUNT(user_id) totalCount
                    FROM ratings
                    GROUP BY user_id
                ) c ON c.user_id = u.user_id
             LEFT JOIN
                (
                    SELECT user_id, COUNT(user_id) totalCount
                    FROM comments
                    GROUP BY user_id
                ) d ON d.user_id = u.user_id

                ORDER BY totalScore DESC LIMIT 25;";
4

2 回答 2

3

LENGTH()返回以字节为单位的字符串长度。你可能想要CHAR_LENGTH(),因为它会给你实际的字符。

SELECT user_id, review, COUNT(user_id) totalCount
FROM reviews
WHERE CHAR_LENGTH(review) > 100
GROUP BY user_id, review

你也没有GROUP BY正确使用。

请参阅文档

于 2013-02-22T20:42:09.300 回答
0

您想要的查询是:

LEFT JOIN
                (
                    SELECT user_id, COUNT(user_id) totalCount,
                           sum(case when length(review) > 100 then 1 else 0 end
                              ) as NumLongReviews
                    FROM reviews
                    GROUP BY user_id
                ) b ON b.user_id= b.user_id 

这包括评论和“长”评论。该计数是使用case嵌套在sum()函数中的语句完成的。

于 2013-02-22T21:29:26.820 回答