【发布时间】:2016-09-05 04:29:47
【问题描述】:
我正在使用左连接加入三个表“客户”、“客户地址”和“国家”,因为我允许客户拥有一个或没有地址。 目前我有 13k 多个客户,查询大约需要 40 秒。我尝试了内部加入,但在这种情况下,我没有得到没有地址的客户。 'ON' 中的所有列都已编入索引,但差别不大。 这是我的查询:
SELECT DISTINCT *,
CASE
WHEN customer_address.customerid is NULL THEN customer.customerid
ELSE customer_address.customerid
END as customerid,
CASE
WHEN address1 = '' THEN 'NA'
ELSE address1
END as address1
FROM customer
LEFT JOIN customer_address ON customer.customerid = customer_address.customerid
LEFT JOIN country ON country.id = customer_address.country
WHERE deleted='0'
ORDER BY customer.customerid
DESC
LIMIT 0, 10
任何帮助将不胜感激
编辑:
下面是对三个表的“解释”:
客户
Field Type Null Key Default Extra
customerid int(12) NO PRI NULL auto_increment
forename varchar(128) YES NULL
surname varchar(128) YES NULL
company varchar(64) YES NULL
tel varchar(32) YES NULL
tel2 varchar(32) YES NULL
fax varchar(32) YES NULL
mob varchar(32) YES NULL
email varchar(255) YES NULL
date_reg date YES NULL
last_update datetime YES NULL
deleted int NO
客户地址
Field Type Null Key Default Extra
addressid varchar(12) NO PRI
customerid varchar(12) YES MUL NULL
address1 varchar(128) YES NULL
address2 varchar(128) YES NULL
town varchar(128) YES NULL
county varchar(128) YES MUL NULL
postcode varchar(12) YES NULL
country int(12) YES NULL
address_date datetime YES NULL
isprimary int NO not
国家
Field Type Null Key Default Extra
id int(12) NO PRI 0
country varchar(255) YES NULL
目前没有删除!='0'
编辑 2:
查询说明:
id select_type table partitions type possible_keys key key_len ref rows filtered Extra
1 SIMPLE customer NULL ALL deleted NULL NULL NULL 13082 99.98 Using where; Using temporary; Using filesort
1 SIMPLE customer_address NULL ALL NULL NULL NULL NULL 9983 100.00 Using where; Using join buffer (Block Nested Loop)
1 SIMPLE country NULL eq_ref PRIMARY,id PRIMARY 4 db_name.customer_address.country 1 100.00 NULL
编辑 3:
1 SIMPLE customer NULL index NULL customerid 4 NULL 1 10.00 Using where; Using temporary
1 SIMPLE customer_address NULL ALL NULL NULL NULL NULL 9983 100.00 Using where
1 SIMPLE country NULL eq_ref PRIMARY,id PRIMARY 4 db_name.customer_address.country 1 100.00 NULL
【问题讨论】:
-
我们在
deleted列上有索引吗? -
真的有必要吗?删除它们,看看需要多长时间
-
不使用 Distinct,不使用 Case-Then-Else 的...的性能如何?
-
能否请您添加
explain plan、create table以及删除了多少行=0? -
您能否为查询添加解释?