内连接(选择。来自)

时间:2012-10-23 06:39:50

标签: sql

我需要获取用户发布的最后一条记录。如果我想按照

之前的顺序进行排序,下面的查询将获得我需要的信息
select a.client_id, a.client, b.title, b.type, b.created 
  from profile_users a, node b 
 where a.uid = b.uid 
   and b.type = 'event' 
   and a.status=1 
   and a.client_id in (select c.client_id 
                         from profile_users c, follows d 
                        where c.uid = d.followed_id 
                          and d.following_id =3) 
 group by a.client_id 
 order by a.client_id,
          b.created desc

我尝试使用内部联接重写查询,但没有获得所需的结果。我需要编写此查询,以便在检查下表中的记录后获取client_id。我需要一些帮助来修复此查询。

select b.client_id, b.client, a.title, a.created
  from node a 
 inner join profile_users b on a.uid=b.uid 
 inner join (select c.client_id
               from profile_users c 
              inner join follows d on c.uid=d.followed_id
              where c.status = 1
                and d.following_id = 3
              order by c.client_id
             ) as X1

2 个答案:

答案 0 :(得分:0)

使用sql“partition by”它将允许您对没有分组的记录进行排序。

http://learnsqlserver.in/2/Partition-By-Clause.aspx

最好在group by上使用。

答案 1 :(得分:0)

您需要使用共同相关的子查询来确定最后一篇文章:

select a.client_id, a.client, b.title, b.type, b.created 
  from profile_users a
    join node b on a.uid = b.uid 
 where b.type = 'event' 
   and a.status=1 
   and a.client_id in (select c.client_id 
                         from profile_users c
                           join follows d on c.uid = d.followed_id
                        where d.following_id = 3) 
   and b.created = (select max(n2.created) 
                    from node n2
                    where n2.uid = a.uid)
 order by a.client_id,
          b.created desc

我还使用'JOIN'关键字将where子句中的旧式隐式连接更改为显式连接。