SQL Server查询选择带有其他相关行的随机行

时间:2019-05-18 17:26:57

标签: sql sql-server

我想随机获得200行SocialMedia_Question。 SocialMedia_Question的每一行在SocialMedia_Answer.Content中都有相关的行。在查询的结果中,我想查看200个随机的SocialMedia_Question.id和在select中指定的其他列。 (问题是每个SocialMedia_Question.id都具有多个相关的SocialMedia_Answer.Content,这使得此查询的结果包含同一问题的多个行。)

我尝试选择top和RAND(),但无法使其正常工作。我不认为简单地选择前200个就行了,因为我需要200个问题以及所有与之相关的数据。

select 
    SocialMedia_Question.id as QuestionID, 
    SocialMedia_Question.Content as Question,
    SocialMedia_Question.CreatedBy as IDQuestionCreator,
    SocialMedia_Question.LikeCount as QuestionLikeCount,
    SocialMedia_Answer.Content as comment, 
    SocialMedia_Answer.createdby as IDCommenter
from  
    SocialMedia_User 
inner join 
    SocialMedia_Question on SocialMedia_Question.CreatedBy = SocialMedia_user.Id 
left join 
    SocialMedia_answer on SocialMedia_Question.id = SocialMedia_answer.QuestionId 
left join 
    SocialMedia_UserDeactivate on SocialMedia_user.id = SocialMedia_UserDeactivate.userid
where 
    ((SocialMedia_UserDeactivate.userid is null)
     and (exists (select null from SocialMedia_Question 
                  where SocialMedia_answer.CreatedBy = SocialMedia_Question.CreatedBy))
    and (SocialMedia_Question.AnswerCount > 10))
order by  
    SocialMedia_user.Id, SocialMedia_Answer.CreatedOn

除了select语句中指定的所有其他列之外,我希望查询结果中有200个随机SocialMedia_Question.id行。非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以按NEWID()订购一组,然后从TOP 200中选择SocialMedia_Question

 select
    SocialMedia_Question.id as QuestionID, 
    SocialMedia_Question.Content as Question,
    SocialMedia_Question.CreatedBy as IDQuestionCreator,
    SocialMedia_Question.LikeCount as QuestionLikeCount,
    SocialMedia_Answer.Content as comment, 
    SocialMedia_Answer.createdby as IDCommenter
from  
    SocialMedia_User 
inner join 
    (select top 200 * FROM SocialMedia_Question order by NEWID()) AS SocialMedia_Question on SocialMedia_Question.CreatedBy = SocialMedia_user.Id 
left join 
    SocialMedia_answer on SocialMedia_Question.id = SocialMedia_answer.QuestionId 
left join 
    SocialMedia_UserDeactivate on SocialMedia_user.id = SocialMedia_UserDeactivate.userid
where 
    ((SocialMedia_UserDeactivate.userid is null)
     and (exists (select null from SocialMedia_Question 
                  where SocialMedia_answer.CreatedBy = SocialMedia_Question.CreatedBy))
    and (SocialMedia_Question.AnswerCount > 10))