Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

sql - MySQL Find Related Articles

I'm trying to select a maximum of 10 related articles, where a related article is an article that has 3 or more of the same keywords as the other article.

My table structure is as follows:

articles[id, title, content, time]
tags[id, tag]
articles_tags[article_id, tag_id]

Can I select the related articles id and title all in one query?

Any help is greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@updated to exclude the searched article itself!

Something along these lines

select *
from articles
inner join (
 select at2.article_id, COUNT(*) cnt
 from articles a
 inner join articles_tags at on at.article_id = a.id
 # find all matching tags to get the article ids
 inner join articles_tags at2 on at2.tag_id = at.tag_id
     and at2.article_id != at.article_id
 where a.id = 1234  # the base article to find matches for
 group by at2.article_id
 having count(*) >= 3  # at least 3 matching keywords
) matches on matches.article_id = articles.id
order by matches.cnt desc
limit 10;  # up to 10 matches required

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...