我有一个查询,该查询从users表中拉出喜欢特定对象的用户。等级存储在ratings表格中。到目前为止,我提出的查询看起来像这样:
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,其他ID分别为1或2个记录-即ID分布不均。
LIMIT
LIMIT 12
有没有一种写此查询的方法来保证(假设一个对象被“点赞”了至少3次),对于列表中的每个ID,我都会得到三个结果?
通过设置行数丝毫变量,然后过滤结果以显示仅第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;