我有两张桌子customers
和他们的contacts
. 一个客户可以有许多联系方式。在这种情况下,我只需要为客户获取最后添加的联系方式。我可以通过subquery
. 但是当数据很大时,我在查询所有客户数据时面临性能不足的问题。
客户表 (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 | |
+-------------------+--------------+------+-----+---------+----------------+
联系人表 (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 | |
+-------------+--------------+------+-----+---------+----------------+
我已经尝试了以下查询,我得到了结果,但是查询很慢。
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);
和
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);
我需要获取客户的公司名称和每个公司名称的最后添加的电话号码。是否有任何优化的方式或不使用子查询的方式来实现这一目标?
解决了
非相关子查询总是比相关子查询提供更好的性能。