我有一个索引(自动增量)和整数值的表.该表长达数百万行.
如何最有效地搜索表格的最后n行中是否出现某个数字?
从@chaos给出的答案开始,但稍作修改:
ORDER BY
如果使用,应始终使用LIMIT
.RDBMS表没有保证隐式顺序.您通常可以按主键的顺序获取行,但您不能依赖它,也不能移植.
如果按降序排序,则无需事先知道表中的行数.
您必须为派生表提供相关名称(也称为表别名).
这是我的查询版本:
SELECT `id` FROM ( SELECT `id`, `val` FROM `big_table` ORDER BY `id` DESC LIMIT $n ) AS t WHERE t.`val` = $certain_number;
可能是一个非常晚的答案,但这很好,很简单.
select * from table_name order by id desc limit 5
此查询将返回您在表中插入的最后5个值(最后5行)的集合
最后5行在mysql中检索
此查询工作正常
SELECT * FROM (SELECT * FROM recharge ORDER BY sno DESC LIMIT 5)sub ORDER BY sno ASC
要么
select sno from(select sno from recharge order by sno desc limit 5) as t where t.sno order by t.sno asc
像分页那样充分利用SORT和LIMIT.如果你想要第i个行块,请使用OFFSET.
SELECT val FROM big_table where val = someval ORDER BY id DESC LIMIT n;
响应Nir:排序操作不一定受到惩罚,这取决于查询计划器的功能.由于此用例对分页性能至关重要,因此有一些优化(参见上面的链接).这在postgres中也是如此,"ORDER BY ... LIMIT可以在没有排序的情况下完成" E.7.1.最后一颗子弹
explain extended select id from items where val = 48 order by id desc limit 10; +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+ | 1 | SIMPLE | items | const | PRIMARY | PRIMARY | 4 | const | 1 | Using index | +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+