如何在不影响脚本性能的情况下将以下查询修改为限制从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.
答案 0 :(得分:4)
答案 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
答案 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");