MySQL限制每个类别的结果

时间:2010-01-04 16:57:53

标签: sql mysql

c_data中的每个项目都在类别/部分中。我想限制每个类别显示的项目数,而不是限制检索的项目总数。显然,如果我在查询中添加类似“限制20”的内容,它总共只能获取20个结果,而不是每个类别20个结果。

   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

该类别的字段是“sectionid”。

2 个答案:

答案 0 :(得分:4)

这个previous post的答案可以帮助您解决这个问题。

修改

它应该可以使用row numbers

我没试过,但这应该有效:

set @section = '';
set @num  = 1;

SELECT y.*
FROM
(
    SELECT
      x.*, 
      @num := if(@section = sectionid, @num + 1, 1) as row_number,
      @section := sectionid
    FROM
    (
        SELECT 
          cm.id AS 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
        FROM c_main AS cm
        JOIN c_data AS cd ON ( cd.sectionid=cm.sectionid )
        ORDER by cd.sectionid ASC, cm.id ASC
    ) x
) y
WHERE y.row_number <= 20;

答案 1 :(得分:4)

MySQL没有任何排名功能,但您可以使用变量来创建伪行号。

使用:

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