[英]Select * Where Column_A and Column_B Are Unique
I've got a table with about 70 million rows.我有一张大约有 7000 万行的表格。 I start by narrowing it down to about 250k rows by selecting from a specific sim_id.
我首先通过从特定的 sim_id 中选择将其缩小到大约 250k 行。
Now, I need to select each first row that has a unique combination of sorted_hand AND ev.现在,我需要 select 每一行都有 sorted_hand 和 ev 的唯一组合。 Put another way, I need to disregard all rows that duplicate an existing row's sorted_hand and ev and select what remains.
换句话说,我需要忽略所有重复现有行的 sorted_hand 和 ev 以及 select 的行。
Table looks like this:表如下所示:
|| id || sim_id || sorted_hand || ev
|| 1 || 1 || 23AA || 2453
|| 2 || 1 || 23AA || 2453
|| 3 || 1 || 23AA || 2453
|| 4 || 1 || 2233 || -548
|| 5 || 1 || 23AK || -296
|| 6 || 1 || 2233 || -548
In the example selection above, I would want the resulting query to select:在上面的示例选择中,我希望得到 select 的查询:
|| 1 || 1 || 23AA || 2453
|| 4 || 1 || 2233 || -548
|| 5 || 1 || 23AK || -296
All of the other rows are disregarded because they have the same exact ev and`sorted_hand as another row.所有其他行都被忽略,因为它们具有与另一行完全相同的 ev 和`sorted_hand 。
You can grab the min(id)
and just GROUP BY the rest of the columns to achieve this:您可以获取
min(id)
并且只需 GROUP BY 列的 rest 即可实现此目的:
SELECT min(id) as id, sim_id, sorted_hand, ev FROM yourtable GROUP BY sim_id, sorted_hand, ev;
In essence, it's not so much "disregarding" but rather grouping records and just returning the first id
encountered for that group.从本质上讲,它不是“忽略”,而是对记录进行分组并返回该组遇到的第一个
id
。
You can filter with a correlated subquery:您可以使用相关子查询进行过滤:
select t.*
from mytable t
where t.id = (
select min(t1.id)
from mytable t1
where t1.sorted_hand = t.sorted_hand and t1.ev = t.ev
)
For performance, you want an index on (sorted_hand, ev, id)
.为了提高性能,您需要
(sorted_hand, ev, id)
上的索引。
Alternatively, If you don't care about sim
, or if it is acceptable to add it to the group, then you can simply use aggregation或者,如果您不关心
sim
,或者如果可以将其添加到组中,那么您可以简单地使用聚合
select min(id) id, sim, sorted_hand, ev
from mytable
group by sim, sorted_hand, ev
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.