0

具有下表示例:

JOBS    
   jobid 
   jobname

COMMENTS  
   jobid 
   userid 
   comment 
   date

USERS   
   userid 
   name

我需要从我一直在尝试的每个jobid中检索最后一条评论,但到目前为止还没有运气。jobid 可以在评论表中多次出现(多个评论等)

4

3 回答 3

0

I would reccomend adding a COMMENTS.ID.

Then look at the max of the COMMENTS.ID.

Alternatly you could

SELECT JOBID, MAX(DATE) FROM COMMENTS GROUP BY JOBID

Then you could join the above view to your COMMENTS table to find the max date. You will need a timestamp on the COMMENTS.DATE.

T

于 2013-07-05T11:03:34.760 回答
0

只要评论中的日期和 jobID 是唯一的,就可以正常工作。如果不是,那么这个答案将为您提供最新的评论,包括领带。

select comment, jobid
from (select max(date) as MaxDate, jobid from comments group by jobid) x
inner join comments c
on c.jobid = x.jobid
and c.date = x.MaxDate
于 2013-07-05T10:59:59.637 回答
0

您可以使用 ROW_NUMBER() 选择每个 jobid 的最后一条评论:

SELECT jobid, userid, comment, date
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY jobid ORDER BY date DESC)'RowRank'
      FROM COMMENTS
     )sub
WHERE RowRank = 1

ROW_NUMBER() 函数根据某些条件为每一行分配一个编号,该PARTITION BY部分中每个项目的编号从 1 开始,当然ORDER BY确定顺序。使用的优点ROW_NUMBER()是您不需要像使用MAX().

如果您想加入其他表以获取所有信息:

SELECT c.jobid, j.jobname, c.userid, u.username, c.comment, c.date
FROM (SELECT *, ROW_NUMBER() OVER (PARTITION BY jobid ORDER BY date DESC)'RowRank'
      FROM COMMENTS
     ) c
JOIN jobs j
  ON c.jobid = j.jobid
JOIN users u
  ON c.userid = u.userid
WHERE c.RowRank = 1
于 2013-07-05T11:00:30.427 回答