0

晚上,

我正在尝试获取MySQL 中每组限制为n的行的输出。我可以让它在没有连接的情况下工作,但有了它我只是害羞。我在这里粘贴了相关表格的转储:

http://pastebin.com/6F0v1jhZ

我正在使用的查询是:

SELECT
   title, catRef, RowNum, pCat, tog
FROM
(
    SELECT
        title, catRef,
        @num := IF(@prevCat=catRef,@num+1,1) AS RowNum,
        @prevCat AS tog,
        @prevCat := catRef AS pCat
    FROM (select @prevCat:=null) AS initvars
    CROSS JOIN 
    (
        SELECT p.title, oi.catRef
        FROM resources p
        INNER JOIN placesRel v ON (p.resId = v.refId)
        INNER JOIN catRel oi ON (p.resId = oi.refId)
        WHERE p.status = 'live' AND v.type = 'res' AND oi.type = 'res'
    ) AS T
) AS U
WHERE RowNum <= 5
ORDER BY catRef

我只是无法让行数增加。或任何其他解决方案将不胜感激。

我正在寻找这样的结果:

title        catRef        RowNum
Title1       1             1
Title2       1             2
Title3       1             3
Title4       2             1
Title5       2             2
Title6       3             1

目前,RowNum 列始终为 1。

4

1 回答 1

0

这有效:

SET @num := 1, @prevCat := 0;
SELECT title, start, end, type, description, linkOut, outType, catRef, row_number
FROM (
SELECT title, start, end, type, description, linkOut, outType, catRef,
@num := if(@prevCat = catRef, @num + 1, 1) as row_number,
@prevCat AS tog,
@prevCat := catRef AS dummy
FROM (
    SELECT title, start, end, resources.type, description, linkOut, outType, catRef
    FROM resources LEFT JOIN placesRel ON placesRel.refId = resId LEFT JOIN catRel ON catRel.refId = resId
    WHERE status = 'live' AND placesRel.type = 'res' AND catRel.type = 'res'
    ORDER BY catRef
) AS w
) AS x WHERE x.row_number <= 4;

您需要将连接的查询放在子查询中,并按要分组的列对其进行排序。使用它的父查询来添加行号。然后,顶级查询将它们粘合在一起。

如果您不将连接的查询放在它自己的子查询中,结果将不会按您希望的顺序排列,而是按照它们在数据库中的顺序出现。这意味着数据没有分组,因此行号不会应用于有序行。

于 2012-05-23T13:06:48.580 回答