MySQL JOIN the most recent row only?

后端 未结 8 1384
傲寒
傲寒 2020-11-28 03:06

I have a table customer that stores a customer_id, email and reference. There is an additional table customer_data that stores a historical record of the changes made to the

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 03:30

    For anyone who must work with an older version of MySQL (pre-5.0 ish) you are unable to do sub-queries for this type of query. Here is the solution I was able to do and it seemed to work great.

    SELECT MAX(d.id), d2.*, CONCAT(title,' ',forename,' ',surname) AS name
    FROM customer AS c 
    LEFT JOIN customer_data as d ON c.customer_id=d.customer_id 
    LEFT JOIN customer_data as d2 ON d.id=d2.id
    WHERE CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%'
    GROUP BY c.customer_id LIMIT 10, 20;
    

    Essentially this is finding the max id of your data table joining it to the customer then joining the data table to the max id found. The reason for this is because selecting the max of a group doesn't guarantee that the rest of the data matches with the id unless you join it back onto itself.

    I haven't tested this on newer versions of MySQL but it works on 4.0.30.

提交回复
热议问题