3

users我有一个查询正在从表中提取喜欢特定对象的用户。评级存储在ratings表格中。到目前为止,我提出的查询如下所示:

SELECT user.id, user.name, user.image
  FROM users
LEFT JOIN ratings ON ratings.userid = user.id
WHERE rating.rating > 0
  AND rating.objectId IN (1,2,3,4)

LIMIT当每个 ID 只需要 3 个左右的结果时,我希望能够在此查询上添加一个,以避免返回所有结果。如果我只是举个LIMIT 12例子,我可能会得到 8 条带有一个 id 的记录,而其他的则各有 1 条或 2 条——即,ID 之间的分布不均匀。

有没有办法编写这个查询以保证(假设一个对象至少被“喜欢”了三次),我得到列表中每个 id 的三个结果?

4

1 回答 1

2

通过设置行号 whit 变量,然后过滤该结果以仅显示第 1-3 行应该有效

SET @last_objectId = 0;
SET @count_objectId = 0;
SELECT id, name, image FROM (
SELECT
 user.id,
 user.name,
 user.image,
 @count_objectId := IF(@last_objectId = rating.objectId, @count_objectId, 0) + 1 AS rating_row_number,
 @last_objectId := rating.objectId
FROM users
LEFT JOIN ratings ON (ratings.userid = user.id)
WHERE
 rating.rating > 0 AND
 rating.objectId IN (1,2,3,4)
ORDER BY rating.objectId
) AS subquery WHERE rating_row_number <= 3;
于 2012-06-27T19:54:32.497 回答