简体   繁体   中英

SELECT n row FROM table1 PER table2


I have 2 table: Cats(category) and post.
I want to SELECT n post per each category.

I have tried this:

SELECT * FROM cat
RIGHT JOIN (SELECT * FROM post WHERE post.CatID=cat.ID LIMIT 3 ) ... 

The problem is MySQL does not recognize cat.ID inside sub query.

Regards

SELECT  a.ID, 
        a.Category,
        b.Description
FROM    Category a
        INNER JOIN Post b
            ON a.ID = b.Cat_ID
WHERE   
(
    SELECT  COUNT(*)
    FROM    Post c
    WHERE   b.Cat_ID = c.Cat_ID AND
            b.ID <= c.ID
) <= 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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