记录Harde学习成长生活的点点滴滴.
« »

一个简单的三表联查例子

今天做项目时,用到的,弄了半天,结果发现其实最简单的语句就能做到
因为我项目的表东西太多
我新建三个表来说

用户登录日志表
UserLoginLog
id 主键 自动增长
userId 外键 用户ID
loginTime 登陆时间
logofftime 登出时间

用户数据表
User
id 主键 自动增长
userName 用户名
userType 外键 用户类型

用户类型表
id 主键 自动增长
typename 户名类型的名称

我想要实现的效果就是
查出 UserLoginLog中的所有数据 但是需要标明是谁登陆的,身份是什么
换句话说就是把userId换成 typename与username

首先写下基础语句

1
select * from [UserLoginLog]

看下结果

1
2
3
4
id          userId      loginTime                                          logoffTime
----------- ----------- --------------------------------------------------
1           1           2009/05/26 07:24:53                                2009/05/26 07:24:56
2           1           2009/05/26 07:25:19                                NULL

OK,开始添油加醋
首先把userid换成useName

1
2
select ull.id,u.userName,ull.logintime,isnull(ull.logofftime,'非正常退出') as loginofftime from UserLoginLog as ull,[User] as u where ull.userId = u.id
--千万别忘了where关联语句

现在结果是这个样子的

1
2
3
4
id          userName         logintime                                          loginofftime
----------- ---------------- --------------------------------------------------
1           admin            2009/05/26 07:24:53                                2009/05/26 07:24:56
2           admin            2009/05/26 07:25:19                                非正常退出

继续,现在把Type弄进来

1
select ull.id,t.typeName,u.userName,ull.logintime,isnull(ull.logofftime,'非正常退出') as loginofftime from UserLoginLog as ull,[User] as u,[UserType] as t where ull.userid=u.id and u.type = t.id
1
2
3
4
id          typeName                   userName         logintime                             loginofftime
----------- ------------------------------------------- ------- -------------------------
1           管理员                         admin            2009/05/26 07:24:53             2009/05/26 07:24:56
2           管理员                         admin            2009/05/26 07:25:19             非正常退出

好了,达到预期效果了
最后加上分页就算搞定了
因为我的语句是在C#程序中组装的
所以大家如果要使用储存过程时
把第一个top 10 的10 换成rowsPerPage 第二个10换成rowsPerPage*pageNum就行了

1
select top 10 ull.id,t.typeName,u.userName,ull.logintime,isnull(ull.logofftime,'非正常退出') as loginofftime from UserLoginLog as ull,[User] as u,[UserType] as t where ull.userid=u.id and u.type = t.id and (ull.id not in (select top 0 ull.id from [UserLoginLog] order by ull.id desc)) order by ull.id desc

写在最后
其实最开始打算用外联来弄,但是写到最后,还是觉得现在写的最为方便……

大家若有其他什么方法,请留言告诉我谢谢

PS:向大家道个歉,上文中子查询的select top 0 ull.id from [UserLoginLog] order by ull.id desc
是错误的
应该写成select top 0 ulll.id from [UserLoginLog] as ulll order by ulll.id desc
因为如果像原来那么写
子查询查出来的是前面主查询查询出来的10条
结果造成的就是无论pagenum传入多少,都将返回0行……

日志信息 »

该日志于2009-05-27 23:42由 harde 发表在DotNet, 数据库分类下, 你可以发表评论。除了可以将这个日志以保留源地址及作者的情况下引用到你的网站或博客,还可以通过RSS 2.0订阅这个日志的所有评论。

相关日志 »

没有评论

发表评论 »

使用新浪微博登陆

返回顶部
分享按钮