Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Each item in c_data is in a category/section. I would like to limit how many items are displayed per category, rather than limiting the total number of items retrieved. Obviously if I add something like "limit 20" to the query, it will only fetch 20 results in total, rather than 20 results per category.

   SELECT cm.id,
                cm.title AS cmtitle,
                cm.sectionid,
                cm.type AS cmtype,
                cd.id,
                cd.time,
                cd.link,
                cd.title,
                cd.description,
                cd.sectionid AS sectionid
      FROM c_main AS cm
      JOIN c_data AS cd ON cd.sectionid=cm.sectionid
     WHERE cd.sectionid=cm.sectionid 
     ORDER by id ASC

The field with the category is "sectionid".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
458 views
Welcome To Ask or Share your Answers For Others

1 Answer

MySQL doesn't have any ranking functionality, but you can use a variable to create a psuedo row number.

Use:

SELECT x.*
  FROM (SELECT cm.id,
               cm.title AS cmtitle,
               cm.sectionid,
               cm.type AS cmtype,
               cd.id AS cd_id,
               cd.time,
               cd.link,
               cd.title,
               cd.description,
               cd.sectionid AS cd_sectionid,
               CASE
                 WHEN @sectionid != cm.sectionid THEN @rownum := 1 
                 ELSE @rownum := @rownum + 1
               END AS rank,
               @sectionid := cm.sectionid
          FROM C_MAIN cm,
               C_DATA cd,
               (SELECT @rownum := 0, @sectionid := NULL) r
         WHERE cm.sectionid = cd.sectionid
      ORDER BY cm.sectionid) x
 WHERE x.rank <= 20
ORDER BY id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...