当前位置:Gxlcms > 数据库问题 > sql server 一对多查询

sql server 一对多查询

时间:2021-07-01 10:21:17 帮助过:19人阅读

用户表 CREATE TABLE [dbo].[T_Userinfo]( [id] [int] IDENTITY(1,1) NOT NULL, --用户ID [name] [nvarchar](50) NULL --用户名字 ) ON [PRIMARY]

 

--给用户表插入测试数据

INSERT INTO [dbo].[T_Userinfo] ([name]) VALUES (张三),(李四),(王五)

 

--登录时间表

CREATE TABLE [dbo].[T_Sign](
[id] [int] IDENTITY(1,1) NOT NULL,
[UserId] [int] NULL,
[SignTime] [datetime] NULL --登录时间
) ON [PRIMARY]

--给登录时间表插入测试数据

INSERT INTO [dbo].[T_Sign]([UserId],[SignTime]) VALUES

(1,2017-03-01 10:55:32),(1,2017-02-01 10:55:32),(1,2017-01-01 10:55:32),
(2,2016-03-02 10:55:32),(2,2017-02-01 10:55:32),(2,2015-01-01 10:55:32),
(3,2017-03-11 10:55:32),(3,2017-02-21 10:55:32),(3,2015-01-01 10:55:32)

 

---查看用户最后登录的时间
select u.id,u.name,s.signtime LastSignTime from T_Userinfo u left join [T_Sign] s on u.id=s.userid
where s.signtime =(select max(signtime) from T_sign where userid=u.id);

select * from t_sign --这句做参考

 

------------------------------------我是分割线-----------------------------------------------------

oracle 中也是这样写.参考这里 https://zhidao.baidu.com/question/513758407.html

 

sql server 一对多查询

标签:sign   arch   ima   where   rac   weight   var   user   arc   

人气教程排行