简体   繁体   English

使用COUNT和HAVING BY进行SELECT查询

[英]SELECT query with COUNT and HAVING BY

How can I modify the below query to limit the number of rows fetched PER userid from the post_list table without affecting the performance of the script (the post_list table is over 10,000 rows here) ? 如何修改以下查询以限制从post_list表中提取的PER userid的行数,而又不影响脚本的性能(此处的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"); 

I need to have 5 posts MAX per post_list.userid. 每个post_list.userid最多需要5个帖子。

So if i have 10 users in my post_list table , the query will return 50 rows. 因此,如果我的post_list表中有10个用户,则查询将返回50行。

EDIT: 编辑:

USERS table 用户表

  id        username
   1          bill
   2          mark
   3          kate

POST_LIST table 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

Here, the query should only return 5 posts from Bill. 在这里,查询应仅返回Bill的5条帖子。

Also, i need the overall number of rows to be limited to 50. 另外,我需要将行的总数限制为50。

Use LIMIT 使用LIMIT

ORDER BY post_id LIMIT 5;

As you commented, you can take a look at this article here which will explain you in detail, How to select the first/least/max row per group in SQL . 正如您所评论的,您可以在此处查看这篇文章,该文章将详细介绍如何在SQL中选择每个组的第一行/最小行/最大行

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

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

You can do this by group by and count. 您可以按分组和计数来执行此操作。 Please try this query. 请尝试此查询。

$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"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM