How to select maximum 3 items per users in MySQL?

前端 未结 3 1275
谎友^
谎友^ 2020-12-14 11:30

I run a website where users can post items (e.g. pictures). The items are stored in a MySQL database.

I want to query for the last ten posted items BUT with the con

3条回答
  •  被撕碎了的回忆
    2020-12-14 12:27

    It's pretty easy with a correlated sub-query:

    SELECT `img`.`id` , `img`.`userid`
    FROM `img`
    WHERE 3 > (
    SELECT count( * )
    FROM `img` AS `img1`
    WHERE `img`.`userid` = `img1`.`userid`
    AND `img`.`id` > `img1`.`id` )
    ORDER BY `img`.`id` DESC
    LIMIT 10 
    

    The query assumes that larger id means added later

    Correlated sub-queries are a powerful tool! :-)

提交回复
热议问题