【问题标题】:How to limit on distinct values and avoiding scan the whole table with order by in the query如何限制不同的值并避免在查询中使用 order by 扫描整个表
【发布时间】:2016-08-02 06:28:15
【问题描述】:

假设这是表格,包含 A、B、C、D、E 列。在按 E 列排序后,我想要 A 列中的有限不同值。

我知道如果没有 order by,下面的查询有效:

set @num := 0, @pa = '';
select A, B, C, D, @num := if(@pa = A, @num, @num+1) as row_number, @pa := A as dummy
from table group by A having row_number <= 100;

但如果在查询末尾添加“order by E”,则“order by”仅对选择 100 行后的结果起作用。

我知道首先对表格进行排序并从 A 列中选择不同的 100 个值是可行的,但是这样扫描整个表格。由于整个表非常大,我不想对其进行整体扫描。

因此我的问题是如何先对其进行排序,然后在不扫描整个表的情况下在 A 列上选择前 100 个不同的值。

-------- 更新 ----------

我试过了

set @num := 0, @pa = '';
select A, B, C, D, @num := if(@pa = A, @num, @num+1) as row_number, @pa := A as dummy
from table where row_number <= 100 order by E;

但这不起作用。

【问题讨论】:

  • 为什么它不起作用?没有您的数据抱歉?只是问问。任何返回值
  • 它有语法问题。查询无法通过这种方式找到“row_number”。
  • 好的,你现在没有问题了吗?
  • 是的,我愿意。我仍然不知道该怎么做。

标签: mysql sql


【解决方案1】:

也许你可以试试这个:

select * from (select A, B, C, D, E from table order by E) as temp 
group by A having count(A) <= 100

【讨论】:

  • 否,'select A, B, C, D, E from table order by E' 扫描整个表。而且这个查询的结果是错误的。
  • 嗯,按列 E 排序将使用该列的索引。默认情况下排序(B-tree)。从这个排序列表中,您只需要 A 的前 100 个不同值,对吗?这个查询可能对select distinct A, B, C, D from table order by E limit 100 有帮助吗?
  • 是的,它几乎可以工作。但是如果我想要 B、C、D 的所有数据在 A 列中具有第一个不同的 100 个值,我现在可以得到的是 'SELECT * from (select A from table group by A order by E) tmp inner join table.A = tmp.A'
  • 也许这个SELECT a,b,c,d,e FROM table WHERE a IN (SELECT a FROM table GROUP BY a ORDER BY e LIMIT 100) ORDER BY e
猜你喜欢
  • 2012-02-13
  • 2019-10-14
  • 1970-01-01
  • 2011-05-27
  • 2021-10-15
  • 1970-01-01
  • 2012-07-06
  • 2019-08-26
  • 1970-01-01
相关资源
最近更新 更多