我知道在此之前必须已经回答过,但我找不到匹配的问题。
使用LIKE '%keyword%'
,我想在MSSQL数据库中搜索多对多数据关系,并将其减少为一对一的结果集。这两个表通过链接表连接在一起。这是我所说的非常简化的版本:
Books:
book_ id title
1 Treasure Island
2 Poe Collected Stories
3 Invest in Treasure Islands
Categories:
category_id name
1 Children
2 Adventure
3 Horror
4 Classic
5 Money
BookCategory:
book_id category_id
1 1
1 2
1 4
2 3
2 4
3 5
我想要做的是搜索标题中的短语(例如'%treasure island%'
)并获取包含搜索字符串的匹配书籍记录以及每本书附带的单个最高匹配Categories
记录 - 我想丢弃较小的类别记录。换句话说,我正在寻找这个:
book_id title category_id name
1 Treasure Island 4 Classic
3 Invest in Treasure Islands 5 Money
有什么建议吗?
答案 0 :(得分:4)
试试这个。过滤您的查找表,然后加入:
With maxCategories AS
(select book_id, max(category_id) as category_id from BookCategory group by book_id)
select Books.book_id, Books.Title, Categories.category_id, Categories.name
from Books
inner join maxCategories on (Books.book_id = maxCategories.book_id)
inner join Categories on (Categories.category_id = maxCategories.category_id)
where Books.title like '%treasure island%'
答案 1 :(得分:1)
尝试:
select * from
(select b.*,
c.*,
row_number() over (partition by bc.book_id
order by bc.category_id desc) rn
from Books b
join BookCategory bc on b.book_id = bc.book_id
join Categories c on bc.category_id = c.category_id
where b.name like '%treasure island%') sq
where rn=1