好好爱自己!

[转]self-join

原文:https://www.cnblogs.com/javafun/archive/2008/04/02/1133793.html

 

自联接就是您自己加入表格时的情况。没有SELF JOIN关键字,您只需编写一个普通连接,其中连接中涉及的两个表都是同一个表。需要注意的一点是,当您自行加入时,必须为表使用别名,否则表名称将不明确。当您想要关联同一个表中的行对(例如父子关系)时,它非常有用。以下查询返回“Kitchen”类别的所有直接子类别的名称。SELECT T2.nameFROM category T1JOIN category T2ON T2.parent = T1.idWHERE T1.name = 'Kitchen'

________________________________

Ref: http://www.udel.edu/evelyn/SQL-Class3/SQL3_self.html

A self-join is a query in which a table is joined (compared) to itself. Self-joins are used to compare values in a column with other values in the same column in the same table.  One practical use for self-joins:  obtaining running counts and running totals in an SQL query.

To write the query, select from the same table listed twice with different aliases, set up the comparison, and eliminate cases where a particular value would be equal to itself.

Example

Which customers are located in the same state (column name is Region)?  Type this statement in the SQL window:

SELECT DISTINCT c1.ContactName, c1.Address, c1.City, c1.Region

FROM Customers AS c1, Customers AS c2

WHERE c1.Region = c2.Region

AND c1.ContactName <> c2.ContactName

ORDER BY c1.Region, c1.ContactName;

The result should look like this:

cust-same-reg-selfjoin-result

Exercise

posted @   立志做一个好的程序员  阅读(145)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2019-12-14 [转]Linux虚拟网络设备之tun/tap
2019-12-14 [转]Linux网络 - 数据包的发送过程
2019-12-14 [转]Linux网络 - 数据包的接收过程
2018-12-14 c语言中pthread的理解和使用
2018-12-14 socket bind 随机端口
2017-12-14 正则表达式的捕获组(capture group)在Java中的使用

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示