如何在1对多关系中编写查询,从sql查询中获取第2表中的随机1条记录

时间:2016-05-15 10:21:32

标签: sql sql-server join

我有3张桌子

    with Album(RankNo,AlbumID, Name, FileName, PhotoID) as
(
select 
rank() over(partition by GA.AlbumID order by GP.photoid) as RankNo ,
GA.AlbumID,GA.Name, GP.FileName, GP.PhotoID, GP.CreatedDate from tblAlbum GA
inner join tblAlbumPhotos GAP on GAP.AlbumID=GA.AlbumID
inner join tblPhotos GP on GP.PhotoID=GAP.PhotoID
)
select RankNo,AlbumID, Name, FileName, PhotoID from Album where RankNo=1

这是从相册和1张照片中获取结果的查询

var elements = WebDriver.FindElements(By.Id("lastdays_day"));

但是,我希望来自tblAlbum表和FileName的结果任意1(随机)来自tblPhotos

1 个答案:

答案 0 :(得分:0)

试试这个(我只更改了你的订单条款):

;with Album(RankNo,AlbumID, Name, FileName, PhotoID) as
(
select 
rank() over(partition by GA.AlbumID order by newId()) as RankNo ,
GA.AlbumID,GA.Name, GP.FileName, GP.PhotoID, GP.CreatedDate from tblAlbum GA
inner join tblAlbumPhotos GAP on GAP.AlbumID=GA.AlbumID
inner join tblPhotos GP on GP.PhotoID=GAP.PhotoID
)
select RankNo,AlbumID, Name, FileName, PhotoID from Album where RankNo=1