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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大