Home > Database > Mysql Tutorial > How to Efficiently Join the Most Recent Row from a Historical Table in MySQL?

How to Efficiently Join the Most Recent Row from a Historical Table in MySQL?

Linda Hamilton
Release: 2025-01-02 15:39:40
Original
487 people have browsed it

How to Efficiently Join the Most Recent Row from a Historical Table in MySQL?

Joining the Most Recent Row in MySQL

Given two tables, customer and customer_data where the latter contains a historical record of customer changes, the task at hand is to retrieve customer information while ensuring only the most recent entry from customer_data is joined to each customer in the customer table.

To accomplish this, consider utilizing the WHERE clause instead of the main query body, as it provides better performance and code readability. Here's an optimized query:

SELECT c.*,
       CONCAT(title, ' ', forename, ' ', surname) AS name
FROM customer c
LEFT JOIN customer_data d
ON c.customer_id = d.customer_id
WHERE d.customer_id = (
    SELECT MAX(customer_id)
    FROM customer_data
    WHERE customer_id = c.customer_id
)
LIMIT 10, 20;
Copy after login

This query ensures that only the most recent row from customer_data is joined for each customer in customer by filtering it within the WHERE clause. The LEFT JOIN ensures that all customers from customer are included in the results, even if they don't have a corresponding entry in customer_data.

Regarding your concerns about using CONCAT and LIKE together, you're correct. CONCAT concatenates strings, and the resulting string can be used with the LIKE operator to perform pattern matching. Your query is valid in that aspect.

The above is the detailed content of How to Efficiently Join the Most Recent Row from a Historical Table in MySQL?. 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