I have two tables customers
and their contacts
. A customer can have many contact details. In a case i need to get only the last added contact details for the customers.I can attain this by subquery
. But when the data is huge, I'm facing performace lack on querying all the customers data.
Customer table (customers_customers)
+-------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| company_name | varchar(150) | NO | | NULL | |
| logo | varchar(100) | NO | | NULL | |
+-------------------+--------------+------+-----+---------+----------------+
Contacts table (customers_customercontacts)
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| email | varchar(100) | YES | | NULL | |
| mobile | varchar(50) | YES | | NULL | |
| customer_id | int(11) | NO | MUL | NULL | |
+-------------+--------------+------+-----+---------+----------------+
I've tried with the folowing queries, I'm getting results, but query is slow.
SELECT
c.id,
c.company_name,
d.mobile
FROM customers_customers AS c
LEFT JOIN customers_customercontacts AS d
ON d.id = (SELECT MAX(id) FROM customers_customercontacts WHERE d.customer_id = d.id);
and
SELECT
c.id,
c.company_name,
d.mobile
FROM customers_customers AS c
LEFT JOIN customers_customercontacts AS d
ON d.id = (SELECT id FROM customers_customercontacts WHERE d.customer_id = d.id
ORDER BY id DESC LIMIT 1);
I need get get the customer's company_names and the last added phone_number of the each company_names. Is there any optimized way or a way without using subquery, to attain this?
Solved
NonCorrelated Subqueries always given better performance over than Correlated Subqueries.