admin

如何在MySQL中优先搜索多个列?

sql

我目前有一个PHP函数(codeigniter),该函数接受一个查询字符串(来自post),并返回相关的MySQL行,如下所示:

$term = $this->input->post("query");
$rows = $this->db->query("SELECT id, title as 'desc' , abbreviation , etc FROM shows WHERE abbreviation LIKE '%".$term."%' OR title LIKE '%".$term."%' OR etc LIKE '%".$term."%'  LIMIT 10; ")->result_array();

这可行,但可以说我的桌子是这样的:

id  title                    abbreviation
--  ----------------------   ------------
1   The Big Bang Theory      TBBT
2   How I Met Your Mother    HMYM
3   a show called tbbt hmym  ASCTM

现在,当用户搜索时tbbt,它将首先返回第三行。但我希望将缩写作为“主要”参数。

因此,如果缩写匹配,请首先返回它,然后查找标题栏。

我想我可以用PHP做到这一点:

// pseudo-code : 
$abbreviation_matches = result("bla bla WHERE abbreviation LIKE term AND NOT title like term");
$title_matches = result("bla bla WHERE NOT abbreviation LIKE term AND title LIKE term");
$result = append($abbreviation_matches , $title_matches);

但是我担心这不会那么有效,因为它涉及2个独立的SQL查询。那么,有没有更有效的方法来做到这一点?最好在一个查询中?

实际情况是有4列,但是只有一列具有优先级,因此其他列的顺序并不重要。

谢谢你的帮助!


阅读 213

收藏
2021-06-07

共1个答案

admin

它可能是解决方案之一:

SELECT id, desc, abbreviation, etc FROM
( 
   SELECT 1 AS rnk,  id, title as 'desc' , abbreviation , etc FROM shows 
   WHERE abbreviation LIKE '%".$term."%'
   UNION 
   SELECT 2 AS rnk,  id, title as 'desc' , abbreviation , etc FROM shows 
   WHERE title LIKE '%".$term."%' 
) tab
ORDER BY rnk
LIMIT 10;

或者您可以通过以下方法实现相同目的:

SELECT  id, desc, abbreviation, etc FROM
(
    SELECT CASE WHEN abbreviation LIKE '%".$term."%' THEN 1 ELSE 2 END As rnk,
    id, title AS desc, abbreviation, etc 
    FROM shows 
    WHERE abbreviation LIKE '%".$term."%' 
    OR title LIKE '%".$term."%' 
) tab
 ORDER BY rnk
 LIMIT 10;
2021-06-07