4

我正在使用 CodeIgniter 和活动记录。我有posts表:

id | title | body | accepted | deleted

一旦用户输入一个单词,如果它在这些帖子中或在这些帖子中,6将建议匹配数据库的帖子。titlebody

我想做的是优先考虑那些在他们里面有这个短语的title帖子,而不是那些只在他们的body. 怎么做?

$query = $this->db->select('id,title,body')
->from('posts')
->where(array('accepted'=>'1'))
->where(array('deleted'=>'0'))
->like('title', $seached_text)
->or_like('body', $seached_text)
->limit(6)
->order_by('title','asc'); 
4

1 回答 1

4

这是 SQL 查询:

SELECT id, title, body
  FROM posts
  WHERE title LIKE '%{KEY}%' OR body LIKE '%{KEY}%'
  ORDER BY CASE
    WHEN (title LIKE '%{KEY}%' AND body LIKE '%{KEY}%') THEN 1
    WHEN (title LIKE '%{KEY}%' AND body NOT LIKE '%{KEY}%') THEN 2
    ELSE 3
    END, title
LIMIT 0, 6;

SQLFiddle 演示

在这种情况下,行首先具有{KEY}intitle和in body,然后行具有在{KEY}其内部title,最后是具有{KEY}in 的行body

您可以使用以下方法在 CodeIgniter 中运行此查询:

$query = $this->db->query('YOUR QUERY HERE');

这是一个例子:

$key = $this->db->escape_like_str($seached_text);

$sql = <<<SQL
SELECT id, title, body
  FROM posts
  WHERE accepted = '1'
    AND deleted = '0'
    AND (title LIKE '%$key%' OR body LIKE '%$key%')
  ORDER BY CASE
    WHEN (title LIKE '%$key%' AND body LIKE '%$key%') THEN 1
    WHEN (title LIKE '%$key%' AND body NOT LIKE '%$key%') THEN 2
    ELSE 3
    END, title
LIMIT 0, 6;
SQL;

$query = $this->db->query($sql);
$result = $query->result_array();
于 2013-08-08T12:38:44.523 回答