使用COUNT和HAVING BY进行SELECT查询

时间:2013-11-05 05:09:28

标签: mysql sql

如何在不影响脚本性能的情况下将以下查询修改为限制从userid获取的行post_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行。

修改

USERS表

  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

此处,查询应仅返回Bill的5个帖子。

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

3 个答案:

答案 0 :(得分:4)

使用LIMIT

ORDER BY post_id LIMIT 5;

正如您所评论的那样,您可以查看本文here,它将详细解释您,如何在SQL 中为每个组选择第一个/最小/最大行。< / p>

答案 1 :(得分: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

答案 2 :(得分: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");