标签/关键字匹配的最佳解决方案是什么?

mar*_*kom 5 sql search many-to-many stored-procedures

我正在寻找数据库中不同记录之间关键字匹配的最佳解决方案.这是一个经典问题,我发现了类似的问题,但没有具体的问题.

我已经完成了全文搜索,连接和子查询,临时表,...所以我真的很想看看你们是如何解决这样一个常见问题的.

所以,假设我有两张桌子; Products并且Keywords它们与第三个表格相关联,Products_Keywords具有经典的多对多关系.

如果我Product在页面上显示一条记录并希望显示前n个相关产品,那么最佳选择是什么?

我们应该考虑到记录可能共享几个关键字,这个事实应该决定顶级相关产品的顺序.

我也对其他想法持开放态度,但由于性能原因,T-SQL将是更好的解决方案.

Jos*_*non 0

好吧,也许像下面这样:

select p.productId, p.name, r.rank
from products p inner join (
/* this inner select should bring in only products that have at least one keyword
=> shared with the requested product, and will count the actual number shared (for ranking)*/
    select related.productId, count(related.productId) as rank
    from
        products_keywords related   inner join 
        products_keywords pk ON (pk.productId = @productId  AND related.keywordId = pk.keywordId)
    where related.productId <> @productId
    group by related.productId
) r on p.productId = r.productId
order by r.rank DESC /* added DESC (not in orignal solution, but needed to put higher ranked on top)*/
Run Code Online (Sandbox Code Playgroud)

现在我严重怀疑这是一个最佳的 sql 语句,但它应该可以完成工作。但我无法验证它,因为我只是从头开始编写它,没有实际的支持表或要测试的数据。