[英]MYSQL - how do i select no more than x rows max with the same field value y?
this question is a bit tricky to formulate, so probably has been asked before. 这个问题的表达有些棘手,所以以前可能有人问过。
i am selecting rows from a table of interrelating data. 我正在从相互关联的数据表中选择行。 i only want a maximum of n rows which have the same value x of some field/column in the table to show up in my set.
我只希望最多有n个行,这些行具有表中某个字段/列的相同值x,以显示在我的集合中。 there is a global limit, in essence i always want the query to return the same amount of rows, with no more than n rows sharing value x.
有一个全局限制,从本质上讲,我始终希望查询返回相同数量的行,共享值x的行不超过n行。 how do i do this?
我该怎么做呢?
here's an example of the data (dots are supposed to indicate that this table is large, let's say 20000 rows of data): 这是一个数据示例(点应表示该表很大,假设有20000行数据):
some_table
+----+----------+-------------+------------+
| id | some_id | some_column | another_id |
+----+----------+-------------+------------+
| 1 | 10 | value | 8 |
| 2 | 10 | value | 5 |
| 3 | 10 | value | 2 |
| 4 | 20 | value | 3 |
| 5 | 30 | value | 9 |
| 6 | 30 | value | 1 |
| 7 | 30 | value | 4 |
| 8 | 30 | value | 6 |
| 9 | 30 | value | 7 |
| 10 | 40 | value | 10 |
| .. | ... | ... | ... |
| .. | ... | ... | ... |
| .. | ... | ... | ... |
| .. | ... | ... | ... |
+----+----------+-------------+------------+
now here's my select: 现在,这是我的选择:
select * from some_table where some_column="value" order by another_id limit 6
but instead of returning rows with another_id = 1 thru 6 i want to get no more than 2 rows with the same value of some_id. 但是我不希望返回不超过another_id = 1到6的行,而希望获得不超过2个具有some_id值的行。 in other words, i'd like to get:
换句话说,我想得到:
result set
+----+----------+-------------+------------+
| id | some_id | some_column | another_id |
+----+----------+-------------+------------+
| 6 | 30 | value | 1 |
| 3 | 10 | value | 2 |
| 1 | 10 | value | 3 |
| 7 | 30 | value | 4 |
| 4 | 20 | value | 8 |
| 10 | 40 | value | 10 |
+----+----------+-------------+------------+
note that the results are ordered by another_id, but there are no more than 2 results with the same value of some_id. 请注意,结果按another_id排序,但是some_id值相同的结果不超过2个。
how can i best (meaning preferably in one query and reasonably fast) get there? 我如何才能最好地实现(最好是在一个查询中并且以合理的速度)到达那里? thanks!
谢谢!
select id, some_id, some_column, another_id from (
select
t.*,
@rn := if(@prev = some_id, @rn + 1, 1) as rownumber,
@prev := some_id
from some_table t
, (select @prev := null, @rn := 0) var_init
where some_column="value"
order by some_id, id
) sq where rownumber <= 2
order by another_id;
First we order by some_id, id in the subquery to do the right calculations. 首先,我们在子查询中按some_id,id进行排序,以进行正确的计算。 Then we order by another_id in the outer query to have correct ordering.
然后,我们通过外部查询中的another_id进行排序,以获得正确的排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.