MySQL全文搜索多行

时间:2017-03-19 22:43:11

标签: mysql full-text-search

我有一个名为essays的表,它与名为paragraphs的表具有1对M的关系。因此,paragraphs表的外键指向essay

我当前遇到的问题是,如果我进行搜索,MySQL会查看每个段落,但不知道多个段落可以指向同一本书。

我的全文搜索看起来像这样:

SELECT DISTINCT *, 
 MATCH(essays.title) AGAINST('my search') as tscore,
 MATCH(paragraphs.content) AGAINST('my search') as cscore
FROM essays 
INNER JOIN paragraphs ON paragraphs.essay_id = essays.id
WHERE 
 MATCH(essays.title) AGAINST('my search')
 OR MATCH(paragraphs.content) AGAINST('my search')
ORDER BY (3 * tscore + cscore) DESC

有没有办法让MySQL在文章的所有段落中搜索某些内容,然后返回该文章?

1 个答案:

答案 0 :(得分:0)

这样的事情对你有用吗?

SELECT essays.id, essays.title,
   MATCH(essays.title) AGAINST('my search') as tscore,
   MATCH(paragraphs.content) AGAINST('my search') as cscore
FROM essays 
   INNER JOIN paragraphs ON paragraphs.essay_id = essays.id
GROUP BY essays.id
   HAVING tscore > 0 OR cscore > 0
ORDER BY (3 * tscore + cscore) DESC;

你也可以使用WHERE子句而不是HAVING,但是你需要:

SELECT essays.id, essays.title,
   MATCH(essays.title) AGAINST('my search') as tscore,
   MATCH(paragraphs.content) AGAINST('my search') as cscore
FROM essays 
   INNER JOIN paragraphs ON paragraphs.essay_id = essays.id
WHERE 
   MATCH(essays.title) AGAINST('my search')
   OR MATCH(paragraphs.content) AGAINST('my search')
GROUP BY essays.id
ORDER BY (3 * tscore + cscore) DESC;

请注意,使用SELECT *时不应使用GROUP BY,因为可能会出现不需要的聚合问题。