doutang9037 2017-04-23 13:04 采纳率: 100%
浏览 127
已采纳

如何在MySQL中使用多个关键字对搜索结果进行分组

I have a database with keywords that are linked to a certain post::

Table word_index: word_id - keyword
Table word_rel: word_id - postId - unique_id


Example word_index:
1 - keyword1
2 - keyword2
3 - keyword3 
...

Example word_rel:
1 - 1 - 1
2 - 1 - 2
3 - 2 - 3
...

Now users may search for one or more keywords (just like Google works).

I use a SQL query, this works fine. However, when they use multiple keywords I want the results to be stricter and only show the results that have both keywords as a match. Now the query returns all posts that have one of the keywords as a match.

SELECT g.postName
FROM
(SELECT gr.postId FROM word_index wi INNER JOIN word_rel gr ON wi.word_id = 
gr.word_id (keyword1,keyword2) ) prr
INNER JOIN posts g ON g.postId = prr.postId
GROUP BY g.postId DESC

So the Select in the FROM (SELECT ...) part selects all matching items. After that it should only show all matches with both keywords and not one of the two.

Can I do this in the last GROUP BY part or do I have to change everything?

  • 写回答

1条回答 默认 最新

  • donglie7268 2017-04-23 13:10
    关注

    You can do this with GROUP BY and HAVING:

    SELECT gr.postId
    FROM word_index wi INNER JOIN
         word_rel gr
         ON wi.word_id = gr.word_id
    WHERE wi.keyword IN (keyword1, keyword2)
    GROUP BY gr.postId
    HAVING COUNT(*) = 2;
    

    You need to construct the IN list from the search string provided. You then need to assign the comparison value in the HAVING based on the number of keywords you want to match.

    Note: You may need to do some pre-processing to be sure that keywords are not entered twice.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀