我正在使用左連接加入三個表'customer','customer_address'和'country',因爲我允許客戶擁有一個地址或沒有地址。 目前我有13k +客戶,查詢大約需要40秒。我嘗試了內部連接,但在這種情況下,我沒有找到沒有地址的客戶。 'ON'中的所有列都被編入索引,但它沒有太大區別。 這裏是我的查詢:只有兩個左連接的SQL查詢非常慢
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
customer_address
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'列? – mitkosoft
這些案件真的有必要嗎?刪除它們並查看需要多長時間 – Matt
如果您不使用Distinct,Case-Then-Else's ...既不是性能如何? – xarmengol