1

我需要从 3 个表中选择一个随机记录并确保我是通过 photoOrder 订购的

Select TOP 1(a.id), a.mls_number, a.parcel_name, a.property_type, a.ownership_type,     b.filename, b.photoOrder, c.county_Name
From property as a
Inner JOIN
listingPhotos as b on a.id = b.ListingID 
LEFT JOIN
counties as C on a.county_name = c.id
WHERE a.isCommercial = 'True'
Order By NEWID()

所以这个查询有效,但我需要确保 b.filename 记录按 b.photoOrder 排序,因此 b.photoOrder 应该始终为 1。 b 表(列出照片)每个属性有多个照片文件,我需要仅选择照片顺序中排名第一的照片。

谢谢

4

1 回答 1

3

您可以子查询您的 listingPhotos 表并限制为 WHERE PhotoOrder = 1:

Select TOP 1(a.id), a.mls_number, a.parcel_name, a.property_type, a.ownership_type,     b.filename, b.photoOrder, c.county_Name
From property as a
Inner JOIN
(SELECT ListingID , filename, PhotoOrder FROM listingPhotos WHERE PhotoORder = 1
       ) as b on a.id = b.ListingID 
LEFT JOIN
counties as C on a.county_name = c.id
WHERE a.isCommercial = 'True'
Order By NEWID()
于 2013-06-07T16:36:43.817 回答