标签:问题 date ons rom 数据 span div color style
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
然后,是我们填充数据;
问题,现在我们要选出:
及:打球又约炮的同学;
有些同学的代码可能是这样的;
SELECT [ID] ,[Actity] ,[UserId] FROM [luck].[dbo].[User_Activity] where [Actity]=‘打球‘ and [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
对啦,这个就是我们表的自连接的使用。
然后我们再来看一道实例:
标签:问题 date ons rom 数据 span div color style
原文地址:http://www.cnblogs.com/mc67/p/7400220.html