一个关于主从表的自连接查询

两个表 主表userinfo 从表postinfo 通过userid关联 一对多的关系
userinfo表
userid username
1jecray    
2yang      
3chen      
4yc        
NULLNULL

postinfo表
PostID| Title |userid|content  |order
1title1    1content1  5
2title2    2content2  4
3title3    1content3  2
4title4    1content4  1
5title5    3content5  5
6title6    3content6  8
7title7    4content7  1
8title8    2content8  2
9title9    2content9  8
NULLNULLNULLNULLNULL
要求: 通过一条sql语句得出 每个用户发表post的orderid值最大的记录
如果orderid是时间就是得出每个用户发表最新帖子的相关信息, 该条信息包括两个表中的信息.

期望结果如下
postid   title     userid   content   orderid   username
1        title1        1    content1      5       jecray    
6        title6        3    content6      8       chen      
7        title7        4    content7      1       yc        
9        title9        2    content9      8       yang   

分两步走:
首先通过sql自连接得出postinfo中的每个用户的orderid值最大的记录
SELECT   DISTINCT  a. *
FROM  postinfo a   where  a.postid  IN
          (
SELECT   TOP   1  postinfo.postid
         
FROM  postinfo
         
WHERE  postinfo.userid  =  a.userid
         
ORDER   BY  orderid  DESC )

在每行的检索中匹配指定条件的记录, 如果换成top 2 可以检索头两条orderid最大的记录

然后进行userinfo和postinfo的连接
SELECT   DISTINCT  a. * ,b. *
FROM  postinfo a  inner   join  userinfo b  on  a.postid  IN
          (
SELECT   TOP   1  postinfo.postid
         
FROM  postinfo
         
WHERE  postinfo.userid  =  a.userid
         
ORDER   BY  orderid  DESC and  a.userid  =  b.userid

便可得出上述效果.自连接的效率不知道怎么样, 反正不会很快了.

如果在oracle里面 还可以通过这样的形式实现
select   *   from  postinfo  where  (uerid,orderid)  in ( select  userid, max (orderid)  as  orderid  from  postinfo  group   by  USERID)
可惜在sqlserver中不能通过

只要涉及到一张表中的同个字段之间或不同字段之间具有逻辑关系 就有可能用到自连接查询
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值