Sql 查询两个以上的数据表,关联查询常用的不同类型的 SQL JOIN
以下是 SQL 中 JOIN 的不同类型:
(INNER) JOIN:返回两个表中具有匹配值的记录
LEFT (OUTER) JOIN:返回左表的所有记录,以及右表中匹配的记录
RIGHT (OUTER) JOIN:返回右表的所有记录,以及左表中匹配的记录
FULL (OUTER) JOIN:当左表或右表有匹配项时,返回所有记录
CROSS JOIN:交叉连接将第一个表的每个记录与第二个表的每个其他记录组合在一起
如下图:
INNER JOIN示例:a表和b表没有通过主键关联,两表都有一个UserId列,通过该列关联,a的UserId数据表有的数据b表的UserId不一定有,代码如下:
SELECT COUNT(a.UserId) AS Num, a.UserId, b.DomianPrice_Daily, b.DomianPrice_Monthly, b.DomianPrice_Annual, b.DomianPrice_Time, b.DomianPrice_UpdateTime FROM dbo.DomainData AS a INNER JOIN dbo.DomianPriceData AS b ON a.UserId = b.UserId GROUP BY a.UserId, b.DomianPrice_Daily, b.DomianPrice_Monthly, b.DomianPrice_Annual, b.DomianPrice_Time, b.DomianPrice_UpdateTime
执行结果如下:
如果以a表数据为准,a表UserId有的数据b表没有,b表没有的数据用Null只显示,这是就可以通过”LEFT (OUTER) JOIN“或”FULL (OUTER) JOIN“完成,代码如下:
SELECT COUNT(a.UserId) AS Num, a.UserId, b.DomianPrice_Daily, b.DomianPrice_Monthly, b.DomianPrice_Annual, b.DomianPrice_Time, b.DomianPrice_UpdateTime FROM dbo.DomainData AS a FULL|LEFT OUTER JOIN dbo.DomianPriceData AS b ON a.UserId = b.UserId GROUP BY a.UserId, b.DomianPrice_Daily, b.DomianPrice_Monthly, b.DomianPrice_Annual, b.DomianPrice_Time, b.DomianPrice_UpdateTime
执行结果如下:
CROSS JOIN:将第一个表的每个记录与第二个表的每个其他记录组合在一起,这是会强调以第一个表内容关联在一起,会随第一个表数据行数关联显示第二个表,此时b表仅有一条数据,CROSS JOIN是根据a表返回的数据行数,没有数据的以第一行数据返回结果,代码如下:
SELECT COUNT(dbo.DomainData.UserId) AS Num, dbo.DomainData.UserId, dbo.DomianPriceData.DomianPrice_Daily, dbo.DomianPriceData.DomianPrice_Monthly FROM dbo.DomainData CROSS JOIN dbo.DomianPriceData GROUP BY dbo.DomainData.UserId, dbo.DomianPriceData.DomianPrice_Daily, dbo.DomianPriceData.DomianPrice_Monthly
执行结果如下: