这是 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();