[英]SQL Join Query refactoring
我正在嘗試基於特定列聯接3個表。 data_customer(主表),data_customer_Address(Cust_id作為外鍵)和Data_customer_contacts(Cust_id作為外鍵)我已經成功實現了以下查詢的結果:
SELECT cst.cust_companyName AS 'Company Name',
cnt.cntct_fname AS 'Contact First Name',
cnt.cntct_lName AS 'Contact Last Name',
cnt.cntct_mainPhone AS 'Main Phn Number',
cnt.cntct_Mobile AS 'Mobile Number',
cst.cust_mainEmail AS 'Main Email',
cnt.cntct_email AS 'Contact Email',
adr.addressLine1 AS 'Adress line 1',
adr.addressLine2 AS 'Address Line 2',
adr.City AS 'City',
adr.State AS 'State',
adr.pinZip AS 'Pin/Zip Code'
FROM data_customer AS cst,
data_customer_Address AS adr,
data_customer_contacts AS cnt
WHERE cst.[cust_id]='2015Q4'
AND adr.[cust_id] ='2015Q4'
AND cnt.[cust_id]='2015Q4';
但是,Cust_id將動態傳遞到查詢中。 如果我不會在任何一個地方傳遞cust_id,我將獲得笛卡爾積。 我嘗試了其他方法,但無法縮短查詢。
請暗示我有什么方法可以改善查詢或改善效能?
注意*:我在Windows上使用Sqlite。
select cst.cust_companyName as 'Company Name',
cnt.cntct_fname as 'Contact First Name',
cnt.cntct_lName as 'Contact Last Name',
cnt.cntct_mainPhone as 'Main Phn Number',
cnt.cntct_Mobile as 'Mobile Number',
cst.cust_mainEmail as 'Main Email',
cnt.cntct_email as 'Contact Email',
adr.addressLine1 as 'Adress line 1',
adr.addressLine2 as 'Address Line 2',
adr.City as 'City', adr.State as 'State',
adr.pinZip as 'Pin/Zip Code'
from data_customer as cst,
data_customer_Address as adr,
data_customer_contacts as cnt
where
cst.[cust_id]=adr.[cust_id] and cst.[cust_id]=cnt.[cust_id]
and cst.[cust_id]='2015Q4';
sql解析通常會首先通過索引(如果有)或完全掃描來獲取表cst中的記錄,然后運行兩個for ... loop進行內部連接表adr和cnt。在這兩個表中都...循環中,表cst將是“外部表”。
您需要學習正確的join
語法。 這樣,您的查詢就不會出現此類問題。
簡單規則: 請勿在FROM
子句中使用逗號。 始終使用顯式JOIN
。 因此,您的QUERY應該看起來像:
SELECT . .
FROM data_customer cst JOIN
data_customer_Address adr
ON cst.cust_id = adr.cust_id JOIN
data_customer_contacts cnt
ON cst.cust_id = cnt.cust_id
WHERE cst.cust_id = '2015Q4';
瞧瞧 省略參數將永遠不會得到笛卡爾積。 而你只需要一次指定客戶ID。
沒關系,我明白了。
select cst.cust_companyName as 'Company Name',
cnt.cntct_fname as 'Contact First Name',
cnt.cntct_lName as 'Contact Last Name',
cnt.cntct_mainPhone as 'Main Phn Number',
cnt.cntct_Mobile as 'Mobile Number',
cst.cust_mainEmail as 'Main Email',
cnt.cntct_email as 'Contact Email',
adr.addressLine1 as 'Adress line 1',
adr.addressLine2 as 'Address Line 2',
adr.City as 'City', adr.State as 'State',
adr.pinZip as 'Pin/Zip Code'
from data_customer as cst,
data_customer_Address as adr,
data_customer_contacts as cnt
where
cst.[cust_id]=adr.[cust_id] and cst.[cust_id]=cnt.[cust_id]
and
cst.[cust_id]='2015Q4'
如果您認為還有另一種改進的方法,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.