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;";
答案 0 :(得分: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
。
答案 1 :(得分: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()
语句完成。