我需要有关复杂查询的帮助。我有一个Venues
表,一个Tag
表和一个Venues_Tag_lookup
表。当我在屏幕上显示单个场地的细节时,我希望能够展示与当前场地类似的其他场地。
这将需要一个返回前五个场地的查询,这些场地拥有最多匹配的标签。 (我正在使用MSSQL)
这是我的表格外观的简单布局。
Venues_tbl
----------
VenueId
Venue_name
Tag_tbl
---------
TagId
Tag_name
Venues_Tag_lookup
------------------
Venue_tagId
VenueId
TagId
如果您有任何疑问,请询问。
提前致谢。
答案 0 :(得分:1)
SELECT TOP 5
V.Venue_name
FROM
-- this = tags for this venue
Venues_Tag_lookup this
JOIN
-- others = tags for other venues
Venues_Tag_lookup others
--see what matches, there will be a big pile of them
ON this.TagId = others.TagId
JOIN
Venues_tbl V ON others.VenueID = V.VenueID
WHERE
--filter to this and others
this.VenueID = @TheOneOnScreen
AND
others.VenueID <> @TheOneOnScreen
GROUP BY
--collapse to other venues ...
V.Venue_name
ORDER BY
-- ... and simply COUNT matches
COUNT(*) DESC
答案 1 :(得分:-1)
以下查询可能有所帮助:
-- params = @venueId, @tagId select venueId, venueName, (select count * from venues_tag_lookup vtl where vtl.venueid=v.venueid )tagCount from venues_tbl v where venueId in( select venueId from Venues_tag_lookup where tagId = @tagId ) and venueId @venueId order by 3 desc