sqlserver-中表的自链接
Posted 咕咚
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sqlserver-中表的自链接相关的知识,希望对你有一定的参考价值。
sqlserver-表中的自链接
为了方便,我对表进行简化,一个人能有多个活动;
USE [luck] GO /****** Object: Table [dbo].[User_Activity] Script Date: 2017/8/20 15:14:32 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[User_Activity]( [ID] [int] NOT NULL, [Actity] [nchar](100) NULL, [UserId] [int] NULL, CONSTRAINT [PK_User_Activity] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO
然后,是我们填充数据;
问题,现在我们要选出:
及:打球又约炮的同学;(这里查询的是,打球 and 约炮) 不是 打球 or 约炮
有些同学的代码可能是这样的;
SELECT [ID] ,[Actity] ,[UserId] FROM [luck].[dbo].[User_Activity] where [Actity]=\'打球\' and [Actity]=\'约炮\'
---结果却是这样的
聪明一点的同学可能会这样写:(这样写,是错的,因为,我们要的结果是,同时选择(参加了)了打球和约炮)
SELECT [ID] ,[Actity] ,[UserId] FROM [luck].[dbo].[User_Activity] where [Actity]=\'打球\' UNION ALL SELECT [ID] ,[Actity] ,[UserId] FROM [luck].[dbo].[User_Activity] where [Actity]=\'约炮\'
然后,我们再逐步的分析:(下面的代码)
SELECT [ID], [Actity], [UserId] FROM [luck].[dbo].[User_Activity] where [Actity]=\'打球\' GO SELECT [ID], [Actity], [UserId] FROM [luck].[dbo].[User_Activity] where [Actity]=\'约炮\'
结果;
方案一的实现(INTERSECT)
SELECT [UserId] FROM [luck].[dbo].[User_Activity] where [Actity]=\'打球\' --然后求一次交集; INTERSECT
SELECT [UserId] FROM [luck].[dbo].[User_Activity] where [Actity]=\'约炮\'
方案二的实现(INNER JOIN)
SELECT A.[UserId] FROM [luck].[dbo].[User_Activity] AS A INNER JOIN ( SELECT UserId, [Actity] FROM [luck].[dbo].[User_Activity] ) AS B ON A.UserId=B.UserId WHERE A.Actity=\'打球\' and b.Actity=\'约炮\'
方案三(子查询)
SELECT UserId FROM [luck].[dbo].[User_Activity] where [Actity]=\'打球\' AND UserId in ( SELECT UserId FROM [luck].[dbo].[User_Activity] where [Actity]=\'约炮\' )
然后就一步步的,演变成我们的表自链接了~
SELECT M.UserId FROM( SELECT UserId FROM [luck].[dbo].[User_Activity] where [Actity]=\'打球\' ) M, ( SELECT UserId FROM [luck].[dbo].[User_Activity] where [Actity]=\'约炮\') N WHERE M.UserId=N.UserId
到这一步,就已经很接近我们的表的自链接了;
SELECT M.UserId FROM [User_Activity] M, [User_Activity] N WHERE M.[Actity]=\'打球\' AND N.[Actity]=\'约炮\' AND M.UserId=N.UserId
然后,我们再来看一些其他的实例。。。。
以上是关于sqlserver-中表的自链接的主要内容,如果未能解决你的问题,请参考以下文章