Sql server连接3个表并从第3个表中获取最新信息

时间:2016-01-25 17:19:18

标签: sql-server-2008

大家好我有3张桌子如下

Technology_table

Technology_ID     Technology_Name
  10                Asp.Net
  20                  C#

Question_table

QUESTION_ID     Technology_ID    QUESTION_DESCRIPTION
  1                 10            First ques in Asp.net
  2                 20            First ques in C#

Reply_table

QUESTION_ID     Technology_ID    Reply_Date       Reply_Message
  1                 10            2016-01-23        I am first to post
  1                 10            2016-01-24        I am second to post

我编写了以下查询,但未按预期获得结果

select
   FI.QUESTION_ID,FI.QUESTION_TITLE,FI.USER_NAME,FI.DATE_POSTED,
   FI.[DATE_REPLIED],FI.RepliedName,FI.VIEW_COUNT,FI.REPLY_COUNT,
  FI.REPLY_MESSAGE,TT.TECHNOLOGY_ID,TT.TECHNOLOGY_NAME
from FORUM_TECHNOLOGY TT,
(  select distinct
     TQ.TECHNOLOGY_ID,TQ.QUESTION_ID,TQ.QUESTION_TITLE,TQ.USER_NAME,
     TQ.DATE_POSTED,
     TR.[DATE_REPLIED],
     TR.USER_NAME as RepliedName,
     TQ.VIEW_COUNT,TQ.REPLY_COUNT,TR.REPLY_MESSAGE
   from  FORUM_QUESTIONS TQ
   LEFT OUTER JOIN FORUM_REPLIES TR
       ON TR.TECHNOLOGY_ID=TQ.TECHNOLOGY_ID
      and TR.QUESTION_ID = TQ.QUESTION_ID 
      and TR.[DATE_REPLIED] in (
          select MAX(TR.[DATE_REPLIED])
          from FORUM_REPLIES TR
          group by TR.QUESTION_ID
       )
) FI
where FI.TECHNOLOGY_ID =TT.TECHNOLOGY_ID
  and TT.TECHNOLOGY_ID = @TechID

我也试过这种方式

select t1.QUESTION_ID,oa.USER_NAME,oa.REPLY_MESSAGE
from FORUM_QUESTIONS t1
cross apply(select top 1 * from FORUM_REPLIES 
            where QUESTION_ID = t1.QUESTION_ID
            order by DATE_REPLIED desc)oa
join FORUM_TECHNOLOGY t2 on oa.TECHNOLOGY_ID = t2.TECHNOLOGY_ID 
AND oa.QUESTION_ID = t1.QUESTION_ID

我想只显示一个而不是重复 enter image description here

有人可以帮助我

1 个答案:

答案 0 :(得分:0)

这假设您的DATE_REPLIED具有有效的时间组件,并且不会被省略或默认为午夜。

SELECT FQ.QUESTION_ID
        , FQ.QUESTION_TITLE
        , FQ.USER_NAME
        , FQ.DATE_POSTED
        , FR.DATE_REPLIED
        , FR.RepliedName
        , FQ.VIEW_COUNT
        , FI.REPLY_COUNT
        , FR.REPLY_MESSAGE
        , TT.TECHNOLOGY_ID
        , TT.TECHNOLOGY_NAME
FROM FORUM_TECHNOLOGY AS TT
INNER JOIN FORUM_QUESTION AS FQ
        ON FQ.TECHNOLOGY_ID = TT.TECHNOLOGY_ID
LEFT OUTER JOIN (
        SELECT QUESTION_ID
                , COUNT(*) AS REPLY_COUNT
                , MAX(DATE_REPLIED) AS DATE_REPLIED
        FROM FORUM_REPLIES
        GROUP BY QUESTION_ID
        ) AS FI
        ON FI.QUESTION_ID = FQ.QUESTION_ID
INNER JOIN FORUM_REPLIES AS FR
        ON FR.QUESTION_ID = FI.QUESTION_ID
                AND FR.DATE_REPLIED = FI.DATE_REPLIED