1

如何修改以下查询以限制中获取 PER 的行数useridpost_list而不影响脚本的性能(这里的 post_list 表超过 10,000 行)?

$sql = query("SELECT userid, post, post_id, id, username 
FROM post_list, users
WHERE post_list.userid = users.id AND post_id%4 = 0 
ORDER BY post_id"); 

我需要每个 post_list.userid 最多有 5 个帖子。

因此,如果我的 post_list 表中有 10 个用户,则查询将返回 50 行。

编辑:

用户表

  id        username
   1          bill
   2          mark
   3          kate

POST_LIST 表

 post_id    userid    post 
   1           1       foo
   2           3       bar
   3           3       baz
   4           1       qux
   5           1       foo_1
   6           1       bar_1
   7           1       baz_1
   8           1       qux_1

在这里,查询应该只返回比尔的 5 个帖子。

另外,我需要将总行数限制为 50。

4

3 回答 3

4

采用LIMIT

ORDER BY post_id LIMIT 5;

正如您评论的那样,您可以在这里查看这篇文章,它将详细解释您,如何在 SQL 中选择每个组的第一/最少/最大行

于 2013-11-05T05:10:41.443 回答
2
SELECT pl.*, u.*
FROM users AS u
JOIN (
    SELECT 
        userid,
        SUBSTRING_INDEX(GROUP_CONCAT(post_id ORDER BY post_id DESC), ',', 5) AS last_5_posts
    FROM post_list
    GROUP BY userid
) AS pl5 ON(u.id = pl5.userid)
JOIN post_list AS pl ON (FIND_IN_SET(pl.post_id, pl5.last_5_posts))
ORDER BY pl.post_id DESC
LIMIT 50

示例:http ://sqlfiddle.com/#!2/36f12/30

于 2013-11-05T08:12:39.633 回答
1

您可以按分组和计数来执行此操作。请尝试此查询。

$sql = query("SELECT userid, post, post_id,username, wish_likes FROM post_list, 
users WHERE post_list.userid = users.id AND post_id%4 = 0 group by userid,post,   
 post_id,username, wish_likes having 
count(post_id) <= 5 ORDER BY post_id"); 
于 2013-11-05T05:24:07.593 回答