每组最多n个,具有多个联接

编程入门 行业动态 更新时间:2024-10-08 14:38:57
本文介绍了每组最多n个,具有多个联接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

晚上

我试图在MySQL中获取每组限制为 n 的行的输出.我可以在不使用联接的情况下正常工作,但是我很害羞.我在这里粘贴了相关表的转储:

I am trying to get an output of rows that are limited to n per group in MySQL. I can get it to work without joins, but with it I am just shy. I've pasted a dump of the relevant tables here:

pastebin/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

我只是无法增加行数.否则将不胜感激.

I just can't get the row count to go up. Or any other solution would be greatly appreciated.

我正在寻找这样的结果:

I'm looking for a result like this:

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

目前,RowNum列始终为1.

At the moment, the RowNum column is always 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;

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

You need to put your joined query in a sub-query and order it by the column you want to group by. Use it's parent query to add row numbers. Then, the top-level query glues it all together.

如果不将联接的查询放在自己的子查询中,则结果将不会按您希望的顺序排序,而是按照它们在数据库中的顺序显示.这意味着数据未分组,因此行号将不会应用于有序行.

If you don't put your joined query in it's own sub-query, the results won't be ordered as you wish, but instead will come out in the order they are in the database. This means the data is not grouped, so row numbers will no be applied to ordered rows.

更多推荐

每组最多n个,具有多个联接

本文发布于:2023-11-30 15:16:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650475.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   最多   每组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!