[英]Joins on multiple tables?
Inspired by this article I tried optimizing an export function of a memberlist from our database. 受本文的启发,我尝试从数据库中优化成员列表的导出功能。
The original queries look like this: 原始查询如下所示:
-- 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
The first query returns 180k rows and its performance is not efficient the second query fetch all 180k times. 第一个查询返回18万行,其性能不高,第二个查询获取全部18万次。
I tried doing this instead: 我尝试这样做:
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
The result is only 140k rows. 结果只有14万行。 The reason is probably that I don't get members without a local_store_id
as I intended. 原因可能是我没有想要的没有local_store_id
成员。 And I'm unsure what the problem is. 我不确定是什么问题。
I'm confident that I'm doing something wrong with the joins because of the many tables and WHERE clauses, but I only have experience with doing LEFT/RIGHT joins between two tables. 我确信由于存在许多表和WHERE子句,所以对联接做错了,但是我只有在两个表之间进行LEFT / RIGHT联接的经验。
Can anyone identify the problem? 谁能找出问题所在?
Each JOIN operation should have a corresponding ON statement to tell SQL how to merge the records from the new table. 每个JOIN操作应具有一个对应的ON语句,以告诉SQL如何合并新表中的记录。 It seems like you are doing some of that logic in the WHERE statement, which could be causing the issue. 似乎您在WHERE语句中正在执行某些逻辑,这可能会导致问题。
Also, as far as getting members without a local_store_id, it could be the fact that you are doing an inner join on stores, so your result set only has members that have a corresponding row in stores based on your join logic. 另外,就获取没有local_store_id的成员而言,这可能是因为您正在商店中进行内部联接,因此根据联接逻辑,结果集中只有在商店中具有对应行的成员。 A left outer join may give you what you're looking for. 左外部连接可能会为您提供所需的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.