【问题标题】:Greatest n-per-group With Multiple Joins具有多个连接的最大 n-per-group
【发布时间】:2012-05-23 02:18:58
【问题描述】:

晚上,

我正在尝试获取 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。

【问题讨论】:

  • 兄弟想要什么?
  • 我在上面的底部发布了更多内容。

标签: mysql sql-order-by inner-join greatest-n-per-group


【解决方案1】:

这行得通:

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;

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多