3

我需要获取用户发布的最后一条记录。如果我可以在 group by 之前进行 order by,下面的查询将获得我需要的信息

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
4

2 回答 2

0

使用 sql "partition by" 它将允许您对记录进行排序而无需分组。

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

这最好在 group by 上使用。

于 2012-10-23T07:47:19.247 回答
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 子句中的旧式隐式连接更改为显式连接。

于 2012-10-23T08:14:09.403 回答