我有一張照片子表,所以一個職位可以有很多照片,其中一個照片表列是[優先]。SQL Server +選擇與子表項目記錄
,我需要選擇從崗位表中的記錄,只有有另一個表中的最高優先級的照片:
所以結果應該是這樣的:
Photo Post
pic1 Article1
picX Article2
目前我的結果顯示爲
Photo Post
pic1 Article1
pic2 Article1
picX Article2
與此查詢:
SELECT [Photo],
[PostTitle]
FROM [Post] sp
INNER JOIN [PostPhotos] spp
ON (sp.AutoId = spp.PostId)
WHERE sp.[AutoId] IN (SELECT [PostID]
FROM [Favorites]
WHERE [UserId] = 'UserXXX')
我嘗試沒有成功連接查詢:
SELECT photo,
[PostTitle],
[AskingPrice]
FROM (SELECT sp.[AutoId],
[PostTitle]
FROM [SellPost] sp
WHERE sp.[AutoId] IN (SELECT [PostID]
FROM [Favorites]
WHERE [UserId] = 'UserId'))a
full OUTER JOIN(SELECT TOP 1 [PostId],
[photo]
FROM [PostPhotos] spp
WHERE PostId IN (SELECT [PostID]
FROM [Favorites]
WHERE [UserId] = 'UserXXX')
ORDER BY [Priority] ASC)b
on (a.AutoId = b.PostId)
order by a.AutoId;
我的表:
Table Post
PostId, PostTitle
Table PostPhotos
AutoId, PostId, Photo, Priority --> 1 post can have many photos
有人可以請您幫助。謝謝。