2015-10-30 46 views
-1
select c1.customer_name, c1.customer_street 
from customer as c1, customer as c2 

where c1.customer_street = c2.customer_street 

and c1.customer_name <> c2.customer_name; 

所以這段代碼是從我在網上找到的練習中取得的。我可以從看它的過程中得到的結果是,它似乎創建了兩個獨立的對象,它們來自同一地點的數據,看起來好像是在比較兩個對象並返回結果。'元組變量',它們是什麼以及爲什麼使用它們? (包括代碼)

我從編程的角度來看它,因爲我的SQL知識是相當基礎的。我只是不明白這個查詢中究竟發生了什麼。有人可以詳細解釋一下嗎?

在此先感謝。

+4

瞭解SQL從一個教程,書籍或實踐。不是來自線上發現的寫得不好的代碼。 –

回答

3

簡答:該查詢會給你所有在你的餐桌上有鄰居的顧客。

行由行:

select c1.customer_name, c1.customer_street

最終,你會從客戶那裏得到的表名和街道的列表。

from customer as c1, customer as c2

您將使用此表兩次,交叉引用對自己(見下文)

where c1.customer_street = c2.customer_street 
and c1.customer_name <> c2.customer_name; 

匹配每個客戶在打擊C2的所有客戶C1,確保了街道匹配和名稱不同(<>是「不等於」的運算符)。

一個簡單的例子:

Name  Street: 
John Doe Baker 
Mary Sue Baker 
Zach Smith Dover 

JD/Baker JD/Baker streets match, name match. CULL. 
JD/Baker MS/Baker streets match, name mismatch. Keep. 
JD/Baker ZS/Dover no street match. CULL. 
MS/Baker JD/Baker streets match, names don't. Keep. 
MS/Baker MS/Baker streets match, name match. CULL. 
MS/Baker ZS/Dover no street match. CULL. 
ZS/Dover JD/Baker no street match. CULL. 
ZS/Dover MS/Baker no street match. CULL. 
ZS/Dover ZS/Dover streets match, name match. CULL. 

Records kept: 

JD/Baker 
MS/Baker 
+0

感謝您的解釋。 – Connor

+0

你能否澄清<>的含義?爲什麼它只用於名稱,而不是街道呢? – Connor

+0

如果<>用於名稱和街道,它將顯着改變查詢的含義。而不是鄰居列表,你最終會得到基本上數據庫中的每個人,有一些重複(在我的答案中,你最終會得到「JD,MS,ZS,ZS」 - 四個「沒有街道匹配「表中的條目,因爲這四行在名稱上也不匹配)。 – Brian

相關問題