我有一个简单的多对多查询,我可以搜索:
SELECT article.*, COUNT(article.id) as hits
FROM article
JOIN article_tag ON article.id = article_tag.article_id
JOIN tag ON tag.id = article_tag.tag_id
WHERE (
tag.title = "Foo"
OR tag.title = "Bar"
OR tag.title = "Foo Bar"
OR article.title LIKE "%Foo%"
OR article.title LIKE "%Bar%"
OR article.title LIKE "%Foo Bar%"
)
AND (article.start <= NOW() OR article.start IS NULL)
AND (article.end > NOW() OR article.end IS NULL)
AND (article.type = 'USER')
AND article.enabled = 1
GROUP BY article.id
ORDER BY hits DESC LIMIT 0, 16
搜索效果不错,但是“点击次数”很长。报告不对,所以排序已关闭。
编辑:我想我现在可以更好地描述我的问题了。如果我将第一行更改为:SELECT article.title, tag.title
并删除GROUP BY和ORDER BY,结果列出匹配的文章标题和所有引用的tag.titles - 所以标签最多(与搜索词匹配或不匹配)的文章产生的点击率最高。
答案 0 :(得分:1)
COUNT(article.id)
计算article.id不为null的所有记录。这都是记录。所以它与COUNT(*)
相同。您正在计算匹配商品标签的数量。
如果您想计算文章数量,可以统计不同的文章ID:
COUNT(DISTINCT article.id)
答案 1 :(得分:1)
如果你这样做会怎么样?试一试
SELECT article.*,X.hits
FROM article
JOIN article_tag ON article.id = article_tag.article_id
JOIN tag ON tag.id = article_tag.tag_id
JOIN
(
select id,COUNT(id) as hits
from article
group by id
) X ON article.id = X.id
WHERE (
tag.title in('Foo','Bar','Foo Bar')
OR article.title LIKE "%Foo%"
OR article.title LIKE "%Bar%"
OR article.title LIKE "%Foo Bar%"
)
AND (article.start <= NOW() OR article.start IS NULL)
AND (article.end > NOW() OR article.end IS NULL)
AND (article.type = 'USER')
AND article.enabled = 1
ORDER BY X.hits DESC LIMIT 0, 16