Home > Database > Mysql Tutorial > How to Efficiently Search for a Number in the Last N Rows of a Large MySQL Table?

How to Efficiently Search for a Number in the Last N Rows of a Large MySQL Table?

Susan Sarandon
Release: 2024-12-24 04:18:15
Original
215 people have browsed it

How to Efficiently Search for a Number in the Last N Rows of a Large MySQL Table?

Searching for a Number in Last N Rows of a Large MySQL Table

In this scenario, you have a lengthy table with millions of rows, each having an index (autoincrement) and an integer field. You want to quickly determine whether a specified number appears in the final n rows of the table.

Efficient Solution

The most effective approach entails leveraging a derived table as follows:

SELECT `id` 
FROM (
    SELECT `id`, `val` 
    FROM `big_table` 
    ORDER BY `id` DESC 
    LIMIT $n 
) AS t
WHERE t.`val` = $certain_number;
Copy after login

Explanation:

  • This query establishes a derived table, selecting the id and val columns from the big_table.
  • It sorts the derived table in descending order based on the id column, ensuring that the most recent rows appear first.
  • The LIMIT $n clause restricts the result set to the most recent n rows.
  • Finally, the WHERE condition matches the derived table's val column against the supplied certain_number, identifying rows containing the number in the last n rows.

Benefits:

  • Indexed Search: Sorting by the autoincrement id column takes advantage of the table index, optimizing the search.
  • Performance: Limiting the result set to the last n rows eliminates the need to scan the entire table, significantly enhancing performance.
  • Flexibility: The query allows you to modify the $n parameter to search within different ranges of the last rows.

The above is the detailed content of How to Efficiently Search for a Number in the Last N Rows of a Large MySQL Table?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template