受这篇文章的启发,我尝试从我们的数据库中优化成员列表的导出功能。
原始查询如下所示:
-- First query
SELECT
*
FROM
members_customer_id_0000000169
WHERE
deleted = '0000-00-00 00:00:00'
-- Second query run for every result from first query
SELECT
stores.external_store_id AS local_store_id
FROM
regions,
stores,
stores_reference_members_customer_id_0000000169
WHERE
regions.customer_id = 169
AND
stores.region_id = regions.id
AND
stores_reference_members_customer_id_0000000169.member_id =' . $result['id'] . '
AND
stores_reference_members_customer_id_0000000169.store_id = stores.id
第一个查询返回 180k 行,其性能不高,第二个查询获取所有 180k 次。
我尝试这样做:
SELECT
members_customer_id_0000000169.*,
stores.external_store_id AS local_store_id
FROM
members_customer_id_0000000169
LEFT JOIN
stores_reference_members_customer_id_0000000169
ON
stores_reference_members_customer_id_0000000169.member_id = members_customer_id_0000000169.id
JOIN
regions
JOIN
stores
WHERE
members_customer_id_0000000169.deleted = '0000-00-00 00:00:00'
AND
regions.customer_id = 169
AND
stores.region_id = regions.id
AND
stores_reference_members_customer_id_0000000169.store_id = stores.id
结果只有 140k 行。原因可能是我没有local_store_id
按照我的意图获得成员。而且我不确定问题是什么。
由于有许多表和 WHERE 子句,我确信我在连接上做错了,但我只有在两个表之间进行 LEFT/RIGHT 连接的经验。
任何人都可以识别问题吗?