晚上,
我正在尝试在MySQL中获得每组限制为 n 的行输出。我可以在没有连接的情况下使用它,但有了它,我只是害羞。我在这里粘贴了相关表的转储:
我使用的查询是:
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。
答案 0 :(得分: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;
您需要将已加入的查询放入子查询中,并按要分组的列对其进行排序。使用它的父查询添加行号。然后,顶级查询将它们粘合在一起。
如果您没有将已加入的查询放入其自己的子查询中,则结果将不会按您的意愿进行排序,而是按照它们在数据库中的顺序排列。这意味着数据未分组,因此行号不会应用于有序行。