仅限于相关结果 - MYSQL

时间:2011-06-20 12:57:48

标签: php 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 ";

大家好,我在其他成员的帮助下得到了这个非常好的查询,这在基于相关系统对结果进行排序方面非常有效。因此,当我的两个搜索条件都被填充时,首先会排序这些结果。

问题在于,两个标准都不匹配的结果(仅匹配1条标准)显然会显示在结果中,但顺序较低。我想实际上删除这些结果,有没有办法优化这个查询,以便返回的唯一结果是满足这两个标准的结果?

将LIKE更改为=不是一个选项,因为结果字段是textareas所以mysql需要在textareas中搜索关键字。

谢谢

4 个答案:

答案 0 :(得分:1)

    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

答案 1 :(得分:0)

我是否遗漏了某些内容,或者对于符合这两种情况的记录,您总是会得到SUM(Relevance)= 2?

答案 2 :(得分:0)

试试这个:

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

答案 3 :(得分:0)

您可以在HAVING SUM(Relevance) = 2后面的SELECT添加GROUP BY rideid,因为Relevance是匹配了多少条件的计数。 (如果稍后添加更多条件,则需要使用较大的数字替换2以匹配。)

但是,您也可以用更简单的方式编写整个查询:删除子选择UNION ALL,然后执行WHERE cat LIKE '%$keyword%' AND cat2 LIKE '%$keyword2%'。子选择和UNION的重点是使得只能得到一个或另一个的结果。