简体   繁体   English

仅限于相关结果-MYSQL

[英]Limit to only relevant results - MYSQL

SELECT rideid, year, model, rating, SUM(Relevance) as SearchRelevance 
FROM( 
SELECT rideid, year, model, rating, 1 as Relevance FROM cars 
WHERE cat LIKE '%$keyword%' 
UNION ALL 
SELECT rideid, year, model, rating, 1 as Relevance FROM cars 
WHERE cat2 LIKE '%$keyword2%') 
AS t GROUP BY rideid ORDER BY SUM(Relevance) DESC ";

Hi all, I got this awesome query with the help of other members, which works very well in sorting my results based on a relevance system. 大家好,我在其他成员的帮助下得到了这个很棒的查询,它在基于相关性系统对我的结果进行排序时效果很好。 So that when both of my search criteria are filled those results are ordered first. 因此,当我的两个搜索条件都满足时,这些结果将首先排序。

The problem is that the results which don't match both criteria (only match 1 criteria) obviously show up in the results, but in a lower order. 问题在于,两个条件都不匹配(仅匹配1个条件)的结果显然会以较低的顺序显示在结果中。 I want to actually trash those results, is there a way to refine this query so that the only results that come back are the ones that fill both criteria? 我实际上想破坏这些结果,有没有一种方法可以优化此查询,以使返回的唯一结果是满足两个条件的结果?

Changing the LIKE to = is not an option because the result fields are textareas so mysql needs to search inside the textareas for the keyword. 不能将LIKE更改为=,因为结果字段是textareas,因此mysql需要在textareas中搜索关键字。

Thank you 谢谢

    SELECT rideid, year, model, rating, SUM(Relevance) as SearchRelevance 
      FROM( 
        SELECT rideid, year, model, rating, 2 as Relevance FROM cars 
          WHERE cat LIKE '%$keyword%' AND cat2 LIKE '%$keyword2%') 
        AS t GROUP BY rideid ORDER BY SUM(Relevance) DESC

我是否丢失了某些东西,或者对于同时满足两个条件的记录,您将始终获得SUM(Relevance)= 2?

Try this: 尝试这个:

SELECT rideid, year, model, rating, SUM(Relevance) SearchRelevance
FROM( 
    SELECT rideid, year, model, rating, 1 as Relevance FROM cars 
    WHERE cat LIKE '%$keyword%' 
    UNION ALL 
    SELECT rideid, year, model, rating, 1 as Relevance FROM cars 
    WHERE cat2 LIKE '%$keyword2%'
) AS t 
HAVING SearchRelevance > 1
GROUP BY rideid 
ORDER BY SearchRelevance DESC

You could just add HAVING SUM(Relevance) = 2 to the outer SELECT , just after the GROUP BY rideid , since Relevance is a count of how many criteria matched. 您可以仅在GROUP BY rideid之后将HAVING SUM(Relevance) = 2到外部SELECT ,因为Relevance是对匹配的条件数的计数。 (If you add more criteria later, you'll need to replace the 2 with a larger number to match.) (如果以后添加更多条件,则需要将2替换为更大的数字以进行匹配。)

However, you could also write the whole query in a much simpler way: get rid of the sub-select and UNION ALL , and just do WHERE cat LIKE '%$keyword%' AND cat2 LIKE '%$keyword2%' . 但是,您还可以用一种更简单的方式编写整个查询:摆脱子选择和UNION ALL ,然后在WHERE cat LIKE '%$keyword%' AND cat2 LIKE '%$keyword2%' The whole point of the sub-select and UNION was to make it possible to get results that match only one or the other. 子选择和UNION是使获得仅与另一个匹配的结果成为可能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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