2016-05-15 31 views
0

我有3個表如何在1編寫查詢到一對多的關係,從第二表獲得隨機1個記錄在SQL查詢

tblAlbum 
------------------------ 
AlbumID Int 
Name nvarchar(255) 

tblPhotos 
------------------------- 
PhotoID   int 
FileName  nvarchar(255) 

tblAlbumPhotos 
------------------------ 
AlbumPhotoID (P) int 
AlbumID    int 
PhotoID    int 

這是查詢到從相冊中得到的結果和照片1

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 

,但是我想從tblPhotos

+2

按順序使用newid(),並取頂部1 –

回答

0

嘗試tblAlbum表和文件名的任何1(隨機),因此這(我只by子句改變您的順序排列):

;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 
相關問題