'元组变量'它们是什么以及为什么要使用它们? (包括代码)

时间:2015-10-30 19:08:11

标签: sql variables tuples

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的了解非常基础。我只是不明白这个查询中实际发生了什么。有些人可以详细解释一下吗?

提前致谢。

1 个答案:

答案 0 :(得分: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;

将c1中的每个客户与c2中的所有客户进行匹配,确保街道匹配且名称不同(&lt;&gt;是“不等于”的运营商)。

一个简单的例子:

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