此查询通过是否具有与给定关键字列表匹配的标记来获取文章表中的行。我想按照与搜索匹配的标签数量来排序结果。我该怎么做?
SELECT DISTINCT a.*,
FROM `article` a
INNER JOIN article_tags AS at ON at.article_id = a.article_id
INNER JOIN tags AS t ON t.tag_id = at.tag_id
WHERE t.keyword IN ("apples", "bananas", "oranges")
|--- Article Tags ---|
|--article_tag_id----|
|--article_id--------|
|-------tag_id-------|
|--------------------|
|-------Tags---------|
|------tag_id--------|
|------keyword-------|
|--------------------|
答案 0 :(得分:0)
您可以在行中使用某些内容
SELECT a.*, COUNT(t.keyword) as matches
FROM `article` a
INNER JOIN article_tags AS at ON at.article_id = a.article_id
INNER JOIN tags AS t ON t.tag_id = at.tag_id
WHERE t.keyword IN ("apples", "bananas", "oranges")
GROUP BY a.article_id
ORDER BY COUNT(t.keyword) DESC;
如果您只想要不同的关键字,请使用
SELECT a.*, COUNT(DISTINCT t.keyword) as matches
FROM `article` a
INNER JOIN article_tags AS at ON at.article_id = a.article_id
INNER JOIN tags AS t ON t.tag_id = at.tag_id
WHERE t.keyword IN ("apples", "bananas", "oranges")
GROUP BY a.article_id
ORDER BY COUNT(DISTINCT t.keyword) DESC;