我有以下疑问,我希望找到一个更好的方法来做到这一点,因为它看起来不像我这样做...
修改
对不起,我没有说明我只想返回实际符合所有设施的广告!
SELECT TOP 50 Advert.Id
FROM Advert
WHERE Id in(SELECT Advert_id FROM AdvertsToAmenities WHERE Amenity_id = 1 AND Advert_Id = Id)
AND Id in(SELECT Advert_id FROM AdvertsToAmenities WHERE Amenity_id = 3 AND Advert_Id = Id)
AND Id in(SELECT Advert_id FROM AdvertsToAmenities WHERE Amenity_id = 5 AND Advert_Id = Id)
-- OR --
SELECT TOP 50 Advert.Id
FROM Advert
JOIN AdvertsToAmenities a on Advert.Id = a.Advert_id
JOIN AdvertsToAmenities b on Advert.Id = b.Advert_id
JOIN AdvertsToAmenities c on Advert.Id = c.Advert_id
WHERE a.Amenity_id = 1
AND b.Amenity_id = 3
AND c.Amenity_id = 5
我很想知道如何优化这些查询!
答案 0 :(得分:3)
您的查询对我来说很好。另一种选择是使用这样的东西:
SELECT TOP 50 Advert.Id
FROM Advert JOIN AdvertsToAmenities a ON Advert.Id = a.Advert_id
WHERE a.Amenity_id = 1
OR a.Amenity_id = 3
OR a.Amenity_id = 5
GROUP BY Advert.Id
HAVING COUNT(DISTINCT a.Amenity_id) = 3
如果(Advert_Id, Amenity_id)
对是唯一的,您可以放弃DISTINCT
。
答案 1 :(得分:0)
您的查询的以下重组如何,您只需创建一个逗号分隔的特定礼仪ID列表?
SELECT TOP 50
a.[ID]
FROM [Advert] a
INNER JOIN
(
SELECT ata.[Advert_ID]
FROM [AdvertsToAmenities] ata
WHERE ata.[Amenity_ID]
IN (1, 3, 4, 5) -- Your list of amenity IDs
) as ata
ON a.[ID] = ata.[Advert_ID]
这使用动态表语句预先过滤那些适用的设施,然后再加入广告列表。注意,Sql Server将在执行前大量优化子查询。这应该意味着您将从Sql Server提供的所有优化中获得更易于维护的语句的好处。
答案 2 :(得分:0)
*试试这个简单的
SELECT TOP 50 a.Id
FROM Advert a, AdvertsToAmenities b
WHERE a.Amenity_id in ('1','3','5')
and a.Id = b.Amenity_id