开发者

MySQL Subselect Limit

What im trying to do was to list all categories and their posts but only limit posts per category. And exclude a category without any posts.

I did this with two queries though, get all the categories that have posts, loop the results and get X number of posts per category ID.

How can I do this in just 1 query?

EDIT: this is what I accomplished so far..

SELECT p.post_id, c.category_id
FROM category as c
JOIN posts AS p ON p.category_id = c.category_id
WHERE
FIND_IN_SET(p.post_id, (
    SELECT SUBSTRING_INDEX(a.post_ids, ',', 10)
    FROM
    (
        SELECT GROUP_CONCAT(b.post_id) AS post_ids, b.category_id
        FROM posts as b
        开发者_如何学CGROUP BY b.category_id
    ) AS a
    WHERE a.category_id = c.category_id
))


To exclude all categories without any posts do an inner join between category and post. If you want to limit the number of rows returned, use the LIMIT command.


how about something like this

SELECT  `category_name` 
FROM  `categories` 
WHERE  `posts` !=0
LIMIT 0 , 30
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜