gpt4 book ai didi

mysql - 如何修改此查询以按匹配项排序?

转载 作者:行者123 更新时间:2023-11-29 23:58:56 24 4
gpt4 key购买 nike

此查询根据文章表中是否具有与给定关键字列表匹配的标签来获取行。我想按与搜索匹配的标签数量对结果进行排序。我该怎么做?

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-------|
|--------------------|

最佳答案

你可以在行中使用一些东西

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;

关于mysql - 如何修改此查询以按匹配项排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25172465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com