SQL从多个表中随机选择,并按一个表上的特定条件排序

时间:2013-06-07 16:27:35

标签: sql-server tsql

我需要从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.photoOrder对b.filename记录进行排序,因此b.photoOrder应该始终为1。 b表(列出照片)每个属性有多个照片文件,我只需要选择照片顺序中第一张照片。

由于

1 个答案:

答案 0 :(得分: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()