[英]How do I do a dynamic UNION query in MySQL?
mytable
has an auto-incrementing id
column which is an integer, and for all intents and purposes in this case you can safely assume that the higher ID represents a more recent value. mytable
具有一个自动递增的id
列,该列是一个整数, 在这种情况下 ,出于所有意图和目的,您可以放心地假设较高的ID代表一个更新的值。 mytable
also has an indexed column called group_id
which is a foreign key to the groups
table. mytable
还具有一个称为group_id
的索引列,该索引列是groups
表的外键。
I want a quick and dirty query to select the 5 most recent rows for each group_id
from mytable
. 我想要一个快速而肮脏的查询, group_id
从mytable
为每个group_id
选择5个最新行。
If there were only three groups, this would be easy, as I could do this: 如果只有三个组,这将很容易,因为我可以这样做:
SELECT * FROM `mytable` WHERE `group_id` = 1 ORDER BY `id` DESC LIMIT 5
UNION ALL
SELECT * FROM `mytable` WHERE `group_id` = 2 ORDER BY `id` DESC LIMIT 5
UNION ALL
SELECT * FROM `mytable` WHERE `group_id` = 3 ORDER BY `id` DESC LIMIT 5
However , there is not a fixed number of groups. 但是 ,没有固定数量的组。 Groups are determined by the what's in the groups
table, so there is an indeterminate number of them. 组由groups
表中的内容确定,因此它们的数量不确定。
My thoughts so far : 到目前为止我的想法 :
CURSOR
on the groups
table and build a new SQL query string, then EXECUTE
it. 我可以在groups
表上获取CURSOR
并构建一个新的SQL查询字符串,然后EXECUTE
它。 However, that seems really messy and I'm hoping there's a better way of doing it. 但是,这看起来确实很混乱,我希望有一种更好的方法。 CURSOR
on the groups
table and insert things into a temporary table, then select from that. 我可以在groups
表上获取CURSOR
,然后将其插入到临时表中,然后从中进行选择。 However, that also seems really messy. 但是,这似乎也很混乱。 CURSOR
and then start returning rows directly from there. 我不知道我是否只能抓住CURSOR
,然后直接从那里开始返回行。 Is there perhaps something similar to SQL Server's @table
type variables? 是否可能与SQL Server的@table
类型变量类似? To get n most recent rows per group can be best handled by window functions in other RDBMS (SQL Server,Postgre Sql,Oracle etc), But unfortunately MySql don't have any window functions so for alternative there is a solution to use user defined variables to assign a rank for rows that belong to same group in this case ORDER BY group_id,id desc
is important to order the results properly per group 要获得每组n个最近的行,最好由其他RDBMS(SQL Server,Postgre Sql,Oracle等)中的窗口函数来处理,但是不幸的是MySql没有任何窗口函数,因此有一种替代方法是使用用户定义的解决方案在这种情况下,为属于同一组的行分配等级的变量, ORDER BY group_id,id desc
对于按组正确排序结果很重要
SELECT c.*
FROM (
SELECT *,
@r:= CASE WHEN @g = group_id THEN @r + 1 ELSE 1 END rownum,
@g:=group_id
FROM mytable
CROSS JOIN(SELECT @g:=NULL ,@r:=0) t
ORDER BY group_id,id desc
) c
WHERE c.rownum <=5
Above query will give you 5 recent rows for each group_id
and if you want to get more than 5 rows just change where filter of outer query to your desired number WHERE c.rownum <= n
上面的查询将为您每个group_id
最近5行,如果您想获得5行以上,只需将外部查询的过滤器的位置更改为所需的数字WHERE c.rownum <= n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.