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;
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!