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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘