简体   繁体   中英

MySQL fulltext search over multiple rows

I have a table called essays which has a 1-to-M relationship with a table called paragraphs . Therefore, the paragraphs table has foreign key pointing to essay .

The current problem I have is that, if I make a search, MySQL will look at each individual paragraph, but has no idea that multiple paragraphs can point to the same book.

My fulltext search looks like this:

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

Is there a way to make MySQL search for something across all the paragraphs of an essay and just return that essay?

Does something like this work for you?

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;

You could also use WHERE clause instead of HAVING, but then you need to:

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;

Note that you should not use SELECT * when using GROUP BY because of unwanted aggregation issues that might pop up.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM