MySQL:任何方法可以将这些N个查询转换为更少的查询?

时间:2012-03-21 21:37:18

标签: mysql sql greatest-n-per-group sql-optimization

我有一个user_id整数的列表N,例如

[1001, 1023, 13452, 1679834, ...]

和一张表:

CREATE TABLE content (
  id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
  user_id INT,
  content VARCHAR(100),
  score INT
);

我需要从N获取user_id个整数,并为每个user_id获取具有最高content的前3个score。所以基本上我需要运行此查询N次:

SELECT *
FROM content
WHERE user_id=1001
ORDER BY score DESC
LIMIT 3;

N可能是一个非常大的数字。所以我非常希望避免逐个运行这些查询。

有没有办法减少我需要运行的查询数量?或许某种批量选择?

1 个答案:

答案 0 :(得分:1)

这应该有效:

$str_ids = implode(', ', $arr_ids);

SELECT id, user_id, content, score
FROM (  SELECT *, (@rownum := @rownum + 1) AS rownum, 
            case when @user_id IS NULL then @user_id := c.user_id when @user_id != c.user_id then CONCAT(@rownum := 0, @user_id := c.user_id) AS dummy_value
        FROM (  SELECT *
                FROM content
                WHERE user_id IN ({$str_ids})
                ORDER BY user_id ASC, score DESC) AS c, (@rownum := 1, @user_id := NULL) AS vars
        HAVING rownum <= 3

也许有更好的方法来做到这一点。如果是这样;让我知道!