我正在使用CodeIgniter和活动记录.我有帖子表:
id | title | body | accepted | deleted
用户键入单词后,如果数据库中的标题或正文中包含6个匹配数据库的帖子,则将建议该数据库.
我想做的是,将那些标题中带有该短语的帖子优先于那些仅在正文中具有这些短语的帖子.怎么做?
$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');
解决方法:
这是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;
在这种情况下,首先在标题和正文中都包含{KEY}的行,然后在标题中包含{KEY}的行,最后在正文中具有{KEY}的行.
您可以使用以下命令在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();