We have two customer related tables below and a query with red rows for the undesired results. We are trying to get the results for each customer in customer_data
to include their respective latest phone_number
(from the customer_phones
table based on theupdated
field) that is default and not deleted (shown in query below). The customer_data.customer_id
is the same as customer_phones.user_id
and where we do the left join on.
1) DB table name/data
customer_data
customer_phones
2) Query
SELECT cd.id, cd.customer_id, cd.customer_name, cp.phone_number, cp.updated
FROM customer_data cd
LEFT JOIN customer_phones cp ON cp.user_id=cd.customer_id
AND cp.is_default_phone='1' AND cp.deleted IS NULL
ORDER BY cd.id
3) Results (with undesired rows in red)
The red rows are undesired since each customer should only have one phone number that is both default and updated latest (in case they have more than one default number the one with the latest updated would be the correct one to pull into the results).
We expect these table to have a lot of fields in a few months and want to make sure we don't have a solution with an n+1 issue if using a subquery of some sort. So what would be the most efficient way to query the tables to get the desired results above but without the red undesired rows?