我有一个名为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在文章的所有段落中搜索某些内容,然后返回该文章?
答案 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
,因为可能会出现不需要的聚合问题。