sql内部连接

Organizations are generating and analyzing unmatched volumes of data with each passing minute. In this article, we will demonstrate how we can employ SQL Inner Join to query and access data from multiple tables that store this incessantly growing data in the SQL databases.

企业每分钟都会生成和分析无与伦比的数据量。 在本文中,我们将演示如何使用SQL内部联接来查询和访问多个表中的数据,这些表将不断增长的数据存储在SQL数据库中。

SQL联接 (SQL Joins)

Before we get started with SQL Inner Join, I would like to call out SQL Join here, Join is the widely-used clause in the SQL Server essentially to combine and retrieve data from two or more tables. In a real-world relational database, data is structured in a large number of tables and which is why, there is a constant need to join these multiple tables based on logical relationships between them. There are four basic types of Joins in SQL Server – Inner, Outer (left, right, full), Self and Cross join. To get a quick overview of all these joins, I would recommend going through this link, SQL Join types overview and tutorial.

在我们开始使用SQL内部联接之前,我想在这里称呼SQL Join, Join是SQL Server中广泛使用的子句,从本质上讲是从两个或多个表中合并和检索数据。 在现实世界的关系数据库中,数据由大量表构成,这就是为什么始终需要基于它们之间的逻辑关系将多个表联接在一起的原因。 SQL Server中的联接有四种基本类型-内部联接,外部联接(左,右,完全联接),自联接和交叉联接。 为了快速了解所有这些联接,我建议您仔细阅读该链接, SQL联接类型概述和教程 。

This article targets all about the Inner Join in SQL Server, so let’s head over to it.

本文针对有关SQL Server中的内部联接的所有内容,因此让我们开始吧。

SQL内部联接的定义 (Definition of SQL Inner Join)

Inner Join clause in SQL Server creates a new table (not physical) by combining rows that have matching values in two or more tables. This join is based on a logical relationship (or a common field) between the tables and is used to retrieve data that appears in both tables.

SQL Server中的内部联接子句通过组合两个或多个表中具有匹配值的行来创建新表(非物理表)。 此联接基于表之间的逻辑关系(或公共字段),用于检索出现在两个表中的数据。

Assume, we have two tables, Table A and Table B, that we would like to join using SQL Inner Join. The result of this join will be a new result set that returns matching rows in both these tables. The intersection part in black below shows the data retrieved using Inner Join in SQL Server.

假设我们有两个表,表A和表B,我们希望使用SQL内部联接进行联接。 联接的结果将是一个新的结果集,该结果集将在这两个表中返回匹配的行。 下面黑色的相交部分显示了使用SQL Server中的内部联接检索的数据。

SQL Server内部联接语法 (SQL Server Inner Join Syntax)

Below is the basic syntax of Inner Join.

以下是内部联接的基本语法。

SELECT Column_list
FROM TABLE1
INNER JOIN TABLE2
ON Table1.ColName = Table2.ColName

选择列列表
从表1
INNER JOIN TABLE2
开启Table1.ColName = Table2.ColName

Inner Join syntax basically compares rows of Table1 with Table2 to check if anything matches based on the condition provided in the ON clause. When the Join condition is met, it returns matched rows in both tables with the selected columns in the SELECT clause.

内部联接语法基本上将表1的行与表2进行比较,以根据ON子句中提供的条件检查是否有任何匹配项。 当满足Join条件时,它将在两个表中返回匹配的行,并在SELECT子句中选择列。

SQL Inner Join clause is the same as Join clause and works the same way if we don’t specify the type (INNER) while using the Join clause. In short, Inner Join is the default keyword for Join and both can be used interchangeably.

SQL内部联接子句与Join子句相同,并且如果我们在使用Join子句时未指定类型(INNER),则以相同的方式工作。 简而言之,“内部连接”是“连接”的默认关键字,并且两者可以互换使用。

Note – We will use the keyword ‘Inner’ Join in this article for the sake of more clarity. You can omit it while writing your queries and can use only ‘Join’ as well.

注–为了更加清楚起见,我们在本文中将使用关键字“ Inner” Join。 您可以在编写查询时忽略它,也可以仅使用“加入”。

SQL内部联接行动 (SQL Inner Join in action)

Let’s try to understand the concept of Inner Join through an interesting data sample that deals with a Pizza Company and its food distribution. I am going to create two tables first – table ‘PizzaCompany’ that manages different branches of Pizza outlets in a few cities and table ‘Foods’ that stores food distribution details across these companies. You can execute the code below to create and populate data into these two tables. All this data is hypothetical and you can create in any of your existing databases.

让我们尝试通过一个有趣的数据样本来了解内部连接的概念,该数据样本涉及比萨公司及其食品分配。 我将首先创建两个表–表“ PizzaCompany”(表在几个城市管理比萨饼店的不同分支)和表“食物”(表)存储这些公司之间的食品分配详细信息。 您可以执行下面的代码来创建数据并将其填充到这两个表中。 所有这些数据都是假设的,您可以在任何现有数据库中创建。

CREATE TABLE [dbo].[PizzaCompany]
([CompanyId] [int] IDENTITY(1,1) PRIMARY KEY CLUSTERED,[CompanyName] [varchar](50) ,[CompanyCity] [varchar](30)
)
SET IDENTITY_INSERT [dbo].[PizzaCompany] ON;
INSERT INTO [dbo].[PizzaCompany] ([CompanyId], [CompanyName], [CompanyCity]) VALUES(1,'Dominos','Los Angeles') ;
INSERT INTO [dbo].[PizzaCompany] ([CompanyId], [CompanyName], [CompanyCity]) VALUES(2,'Pizza Hut','San Francisco') ;
INSERT INTO [dbo].[PizzaCompany] ([CompanyId], [CompanyName], [CompanyCity]) VALUES(3,'Papa johns','San Diego') ;
INSERT INTO [dbo].[PizzaCompany] ([CompanyId], [CompanyName], [CompanyCity]) VALUES(4,'Ah Pizz','Fremont') ;
INSERT INTO [dbo].[PizzaCompany] ([CompanyId], [CompanyName], [CompanyCity]) VALUES(5,'Nino Pizza','Las Vegas') ;
INSERT INTO [dbo].[PizzaCompany] ([CompanyId], [CompanyName], [CompanyCity]) VALUES(6,'Pizzeria','Boston') ;
INSERT INTO [dbo].[PizzaCompany] ([CompanyId], [CompanyName], [CompanyCity]) VALUES(7,'chuck e cheese','Chicago') ;SELECT * FROM PizzaCompany:

This is how data in the PizzaCompany table looks like:

这是PizzaCompany表中数据的样子:

Let’s create and populate Foods table now. CompanyID in this table is the foreign key that is referencing to the Primary key of the PizzaCompany table created above.

现在创建并填充Foods表。 该表中的CompanyID是外键,它引用上面创建的PizzaCompany表的主键。

CREATE TABLE [dbo].[Foods]
(
[ItemId] INT  PRIMARY KEY CLUSTERED , [ItemName]  Varchar(50), [UnitsSold] int,CompanyID int,FOREIGN KEY(CompanyID) REFERENCES PizzaCompany(CompanyID))
INSERT INTO [dbo].[Foods] ([ItemId], [ItemName], [UnitsSold], [CompanyId]) VALUES(1,'Large Pizza',5,2)
INSERT INTO [dbo].[Foods] ([ItemId], [ItemName], [UnitsSold], [CompanyId]) VALUES(2,'Garlic Knots',6,3)
INSERT INTO [dbo].[Foods] ([ItemId], [ItemName], [UnitsSold], [CompanyId]) VALUES(3,'Large Pizza',3,3)
INSERT INTO [dbo].[Foods] ([ItemId], [ItemName], [UnitsSold], [CompanyId]) VALUES(4,'Medium Pizza',8,4)
INSERT INTO [dbo].[Foods] ([ItemId], [ItemName], [UnitsSold], [CompanyId]) VALUES(5,'Breadsticks',7,1)
INSERT INTO [dbo].[Foods] ([ItemId], [ItemName], [UnitsSold], [CompanyId]) VALUES(6,'Medium Pizza',11,1)
INSERT INTO [dbo].[Foods] ([ItemId], [ItemName], [UnitsSold], [CompanyId]) VALUES(7,'Small Pizza',9,6)
INSERT INTO [dbo].[Foods] ([ItemId], [ItemName], [UnitsSold], [CompanyId]) VALUES(8,'Small Pizza',6,7)SELECT * FROM Foods

The following table shows data in the Foods table. This table stores information like units sold per food item and also the pizza outlet (CompanyId) that delivers it.

下表显示了食品表中的数据。 该表存储的信息包括每种食品的销售单位,以及存储该食品的比萨店(CompanyId)。

Now, if we would like to see the items and also the units sold by each pizza company, we can combine these two tables with the help of an inner join clause being used on the field CompanyId (in our case this shares a foreign key relationship).

现在,如果我们想查看每个比萨公司的商品以及销售单位,则可以在字段CompanyId上使用内部连接子句的帮助下将这两个表合并(在本例中,这是一个外键关系) )。

 SELECT pz.CompanyCity, pz.CompanyName, pz.CompanyId AS PizzaCompanyId, f.CompanyID AS FoodsCompanyId, f.ItemName, f.UnitsSold
FROM PizzaCompany pz
INNER JOIN Foods f
ON pz.CompanyId = f.CompanyId

Below is the result set of the above SQL Inner Join query. For each row in the table PizzaCompany, Inner Join compares and finds the matching rows in the table Foods and returns all the matching rows as shown below. And if you notice, CompanyId = 5 is excluded from the query result, as it does not make a match in the Foods table.

下面是上述SQL内部联接查询的结果集。 对于表PizzaCompany中的每一行,Inner Join比较并找到表Foods中的匹配行,并返回所有匹配行,如下所示。 并且,如果您注意到,查询结果中排除了CompanyId = 5,因为它在Foods表中不匹配。

With the help of the above result set, we can make out the items and also the count of items delivered by pizza outlets in various cities. For instance, Dominos made a delivery of 7 Breadsticks and 11 Medium Pizza in Los Angeles.

借助以上结果集,我们可以估算出各个城市的比萨饼店所交付的商品以及数量。 例如,多米诺(Dominos)在洛杉矶交付了7个面包棒和11个中号比萨。

在三个表上SQL内部联接 (SQL Inner Join on three tables )

Let’s explore more into this join and suppose three waterparks (looks like summer) get opened in the state and these waterparks outsource food from the pizza outlets mentioned in the table PizzaCompany.

让我们进一步研究这种连接,并假设在该州开设了三个水上乐园(看起来像夏天),这些水上乐园从表PizzaCompany中提到的比萨饼店中外包食品。

I am going to quickly create a table WaterPark and load some arbitrary data into it as shown below.

我将快速创建一个表WaterPark并将一些任意数据加载到其中,如下所示。

CREATE TABLE [dbo].[WaterPark]
([WaterParkLocation] VARCHAR(50),[CompanyId] int,FOREIGN KEY(CompanyID) REFERENCES PizzaCompany(CompanyID)
)
INSERT INTO [dbo].[WaterPark] ([WaterParkLocation], [CompanyId]) VALUES('Street 14',1)
INSERT INTO [dbo].[WaterPark] ([WaterParkLocation], [CompanyId]) VALUES('Boulevard 2',2)
INSERT INTO [dbo].[WaterPark] ([WaterParkLocation], [CompanyId]) VALUES('Rogers 54',4)
INSERT INTO [dbo].[WaterPark] ([WaterParkLocation], [CompanyId]) VALUES('Street 14',3)
INSERT INTO [dbo].[WaterPark] ([WaterParkLocation], [CompanyId]) VALUES('Rogers 54',5)
INSERT INTO [dbo].[WaterPark] ([WaterParkLocation], [CompanyId]) VALUES('Boulevard 2',5)SELECT * FROM WaterPark

And below is the output of this table.

下面是该表的输出。

As the saying goes, the picture is worth a thousand words. Let’s quickly see the database diagram of these three tables with their relationships to understand them better.

俗话说,这幅画值得一千个字。 让我们快速查看这三个表及其关系的数据库图,以更好地理解它们。

Now we are going to include this third table in the SQL Inner Join clause to see how it is going to impact the result set. Per data in the WaterPark table, the three waterparks have been outsourcing food from all the Pizza Companies but Pizzeria (Id=6) and chuck e cheese (Id = 7). Execute the code below to see all the food distribution across the waterparks by the Pizza outlets.

现在,我们将在SQL Inner Join子句中包含第三个表,以查看它如何影响结果集。 根据“水上乐园”表中的数据,三个水上乐园已经外包了所有比萨公司的食品,但比萨店(Id = 6)和查克奶酪(Id = 7)除外。 执行以下代码,查看比萨饼店在水上乐园内所有食物的分配情况。

SELECT pz.CompanyId, pz.CompanyCity, pz.CompanyName,f.ItemName, f.UnitsSold,
w.WaterParkLocation
FROM PizzaCompany pz
INNER JOIN Foods f ON pz.CompanyId = f.CompanyId
INNER JOIN WaterPark w ON w.CompanyId = pz.CompanyId
ORDER BY pz.CompanyId

Based on CompanyId, SQL Inner Join matches rows in both tables, PizzaCompany (Table 1) and Foods (Table 2) and subsequently looks for a match in the WaterPark (Table 3) to return rows. As shown below, with the addition of inner join on WaterPark, CompanyId (6,7 (apart from 5)) are also excluded from the final result set as the condition w.CompanyId = pz.CompanyId is not satisfied for Ids (6,7). This is how SQL Inner join helps to return specific rows of data from multiple tables.

SQL内部连接基于CompanyId来匹配PizzaCompany(表1)和Foods(表2)这两个表中的行,随后在WaterPark(表3)中查找匹配项以返回行。 如下所示,在WaterPark上添加了内部联接后,由于条件w.CompanyId = pz.Ids不满足CompanyId(6, 7)。 这就是SQL内部连接有助于从多个表返回特定数据行的方式。

Let’s dig into SQL Inner Join more with a few more T-SQL clauses.

让我们用更多的T-SQL子句深入研究SQL内部联接。

在内部联接中使用WHERE (Using WHERE with Inner Join)

We can filter records based on a specified condition when SQL Inner Join is used with a WHERE clause. Assume that we would like to get the rows where units sold were more than 6.

当SQL Inner Join与WHERE子句一起使用时,我们可以根据指定条件过滤记录。 假设我们想获得销售量大于6的行。

In the following query, the WHERE clause is added to extract results with value more than 6 for units sold.

在以下查询中,添加了WHERE子句以提取出售的商品的值大于6的结果。

SELECT pz.CompanyId, pz.CompanyCity, pz.CompanyName,f.ItemName, f.UnitsSold
FROM PizzaCompany pz
INNER JOIN Foods f ON pz.CompanyId = f.CompanyId
WHERE f.UnitsSold > 6
ORDER BY pz.CompanyCity

Execute above code in SSMS to see the below result. Four such records are returned by this query.

在SSMS中执行以上代码以查看以下结果。 此查询返回四个此类记录。

通过内部联接使用分组方式 (Using Group By with Inner Join)

SQL Inner Join permits us to use Group by clause along with aggregate functions to group the result set by one or more columns. Group by works conventionally with Inner Join on the final result returned after joining two or more tables. If you are not familiar with Group by clause in SQL, I would suggest going through this to have a quick understanding of this concept. Below is the code that makes use of Group By clause with the Inner Join.

SQL内部联接允许我们将Group by子句与聚合函数一起使用,以按一个或多个列对结果集进行分组。 按常规使用“内部联接”进行分组,将两个或多个表联接后返回的最终结果。 如果您不熟悉SQL中的Group by子句,建议您仔细阅读一下以快速了解此概念。 以下是在内部联接中使用Group By子句的代码。

SELECT pz.CompanyCity, pz.CompanyName, SUM(f.UnitsSold) AS TotalQuantitySold
FROM PizzaCompany pz
INNER JOIN Foods f ON pz.CompanyId = f.CompanyId
GROUP BY pz.CompanyCity, pz.CompanyName
ORDER BY pz.CompanyCity

Here, we intend to obtain total items sold by each Pizza company present in the City. As you can see below, aggregated result in ‘totalquantitysold’ column as 18 (7+11) and 9 (6+3) for Los Angeles and San Diego respectively is computed.

在这里,我们打算获取本市每个比萨公司出售的商品总数。 如下所示,分别计算了洛杉矶和圣地亚哥的“ totalquantitysold”列中分别为18(7 + 11)和9(6 + 3)的汇总结果。

关于Equi和Theta Join的简要说明 (A brief note on Equi and Theta Join)

Before we conclude this article, let’s quickly go over terms, a SQL developer may hear sporadically – Equi and Theta Join.

在总结本文之前,让我们快速浏览一下术语,SQL开发人员可能会偶尔听到– Equi和Theta Join。

平等加盟 (Equi Join)

As the name suggests, equi join contains an equality operator ‘=’ either in the Join clause or in the WHERE condition. SQL Inner, Left, Right are all equi joins when ‘=’ operator is being used as a comparison operator. Usually, when there is a mention of SQL Inner Join, it is considered as an Inner equi Join, in an unusual situation only, equality operator is not used.

顾名思义,等联接在Join子句或WHERE条件中都包含一个等于运算符'='。 当将'='运算符用作比较运算符时,SQL内部,左,右都是等价联接。 通常,当提到SQL内部联接时,它被视为内部等联接,仅在特殊情况下,不使用相等运算符。

To make things easier, I am going to refer to AdventureWorksDW2017 sample database and fire a query against existing tables to demonstrate how equi join looks like.

为了使事情变得更容易,我将参考AdventureWorksDW2017示例数据库并针对现有表进行查询以演示等联接的外观。

SELECT e.EmployeeKey, e.FirstName, e.Title, e.HireDate,
fs.SalesAmountQuota FROM DimEmployee e
INNER JOIN FactSalesQuota fs
ON e.EmployeeKey = fs.EmployeeKey

Theta联接(非设备联接) (Theta Join (Non-equi join))

Non-equi join is basically opposite of equi-join and is used when we join on a condition other than ‘=’ operator. This type is rarely used in practice. Below is an example that makes use of theta join with an inequality operator (<) to evaluate profit by estimating cost and selling prices in two tables.

非等参连接基本上与等参相反,并且在我们以'='运算符以外的条件进行联接时使用。 这种类型在实践中很少使用。 下面是一个示例,该示例使用theta结合不等式运算符(<)通过估计两个表中的成本和售价来评估利润。

SELECT * FROM Table1 T1, Table2 T2 WHERE T1.ProductCost < T2.SalesPrice

结论 (Conclusion)

I hope this article on ‘SQL Inner Join’ provides a comprehensible approach to one of the important and frequently used clauses – ‘Inner join’ in the SQL Server to combine multiple tables. In case you have any questions, please feel free to ask in the comments section below.

我希望这篇有关“ SQL内部联接”的文章提供一种通俗易懂的方法来处理一个重要且经常使用的子句-SQL Server中的“内部联接”以组合多个表。 如有任何疑问,请随时在下面的评论部分中提问。

To continue your learning on SQL Joins, you can refer to below posts:

要继续学习SQL连接,可以参考以下文章:

  • SQL OUTER JOIN overview and examples SQL OUTER JOIN概述和示例
  • SQL Join introduction and overview SQL Join简介和概述

翻译自: https://www.sqlshack.com/a-step-by-step-walkthrough-of-sql-inner-join/

sql内部连接

sql内部连接_SQL内部联接的分步演练相关推荐

  1. 什么时候应该在内部联接上使用交叉应用?

    使用CROSS APPLY的主要目的是什么? 我已经读过(模糊地通过Internet上的帖子),如果您正在分区,则在选择大型数据集时, cross apply会更有效. (想起分页) 我也知道, CR ...

  2. SQL内部连接3个表?

    本文翻译自:SQL Inner-join with 3 tables? I'm trying to join 3 tables in a view; 我试图在一个视图中联接3个表: here is t ...

  3. sql 转置_SQL 如何实现动态的行列转置

    Oracle 和新版 Mysql 里有 pivot 实现行列转置,但实际处理数据时,会碰到一些更复杂的转置情况,pivot 也搞不定,比如: 想转置成: 这个难点在于事先不知道有多少种收入来源,而且每 ...

  4. java.sql.SQLException: ORA-00600: 内部错误代码解决

    java.sql.SQLException: ORA-00600: 内部错误代码解决 简介 出现问题的场景 最终解决方法 简介 最近我们公司生产上的服务器突然报错java.sql.SQLExcepti ...

  5. SQL 错误: ORA-00600: 内部错误代码, 参数: [qcsfbdnp:1], [], [], [], []

    call CREATEZHIBIAOPART2('cy_prop_reason','2014-02-18','PropReason');commit;call CY_ALL_GAOJINSHUCHU( ...

  6. SQL 内部联接 – 如何在 SQL 和 MySQL 中联接 3 个表

    使用数据库时,可能需要将几个不同表中的数据放在一起.本文将向您展示如何操作. 我已经在这里和这里写了关于SQL连接的文章,但让我们先花点时间回顾一下连接是如何工作的,特别是特定于MySQL的语法. S ...

  7. sql编辑器_SQL的弱点(3):缺少静态类型检查

    静态类型检查的重要 如果要把SQL按照编程语言的类型来分类的话,SQL应该属于一种描述型的动态语言. 用动态语言编写的程序,当达到一定的复杂度后,相比强类型静态编译语言来说,更容易出问题. 从2个例子 ...

  8. sql简介_SQL简介

    sql简介 Today, data is the basis of any business. The world of enterprise computing is the epitome of ...

  9. 更新sql语句 sql注入_SQL更新语句– SQL中的更新查询

    更新sql语句 sql注入 SQL Update Statement or Update Query in SQL is used to modify the column data in table ...

最新文章

  1. 2.1算法分析 递归---阶乘
  2. sql查询所有商品的信息_属于菜鸟的sql 干货(7)
  3. 深度学习和目标检测系列教程 4-300:目标检测入门之目标变量和损失函数
  4. linux c之fdopen(int fd, const char *type)使用总结
  5. 晚上我们一起去白码会所玩啊!
  6. 添用户报错:useradd:警告:此主目录已经存在
  7. 【LeetCode】剑指 Offer 39. 数组中出现次数超过一半的数字
  8. Windows操作系统下使用pip安装pygame
  9. Linux操作系统资源 大合集【鸿蒙OS Suse 红帽 BSD CentOS Arch Ubuntu】 | 寻找C站宝藏
  10. 《Adobe Photoshop CS6中文版经典教程(彩色版)》目录—导读
  11. ubuntu挂载移动硬盘时提示Unable to mount
  12. 免费国外视频素材网站
  13. matlab(simulink)里怎么求一个波形的动态平均值
  14. 令人愉快的 Nuxt3 教程 (二): 快速轻松地搭建博客
  15. git删除远端分支命令
  16. Pico VR 一体机初测
  17. 投标任性,围标串标一查实,扫黑除恶,现在投标必须签订一样协议
  18. Kali linux学习入门-Kali菜单中各工具功能
  19. 1411: 喜闻乐见的a+b(20进制)
  20. HTML 访问本地 Markdown 文件

热门文章

  1. sql string转number_少用 string.Format
  2. python灰度图cv2到plt变颜色_python中plt.imshow与cv2.imshow显示颜色问题
  3. RxAndroid 的基本使用
  4. C/C++ 变量的初始化
  5. Grid使用 ComboBox Binding DateTime Format WPF
  6. 数据结构与算法(js)
  7. xcode高版本常见的RN本地启动报错
  8. 数据结构与算法(updating....)
  9. 行内元素、块级元素和行内块级元素
  10. ★LeetCode(39)——组合总和(JavaScript)