我有以下方法来创建一个搜索查询,该搜索查询按出现次数对搜索词进行评分:
public function findAll($search, array $data = []) {
$query = DB::query("
SELECT
SQL_CALC_FOUND_ROWS
*,
SUM(MATCH(text) AGAINST('{$search}' IN BOOLEAN MODE)) as score
FROM " . DB::prefix() . "search_index
WHERE MATCH(text) AGAINST('{$search}' IN BOOLEAN MODE)
OR text LIKE '%{$search}%'
GROUP BY language_id, type, object_id
ORDER BY score DESC
LIMIT " . (int)$data['start'] . ", " . (int)$data['limit'] . "
");
$count = DB::query("SELECT FOUND_ROWS() AS total");
return [
'count' => (int)$count->row['total'],
'query' => $query->rows
];
}
这很好用,但是我需要在tag
表中添加一个查询,这样它就会增加分数,并为主查询中可能尚不存在的内容添加项目到数组:
$tags = DB::query("
SELECT * FROM " . DB::prefix() . "tag
WHERE tag = '{$search}'
");
关于如何在主查询中实现这一点的任何想法,以便我只执行一个查询?
答案 0 :(得分:1)
我能够将这些与UNION查询结合起来:
$query = DB::query("
(SELECT
SQL_CALC_FOUND_ROWS
type, object_id, language_id,
SUM(MATCH(text) AGAINST('{$search}' IN BOOLEAN MODE)) as score
FROM " . DB::prefix() . "search_index
WHERE MATCH(text) AGAINST('{$search}' IN BOOLEAN MODE)
OR text LIKE '%{$search}%'
GROUP BY language_id, type, object_id
ORDER BY score DESC
LIMIT " . (int)$data['start'] . ", " . (int)$data['limit'] . ")
UNION DISTINCT
(SELECT
section, element_id, language_id, tag
FROM " . DB::prefix() . "tag
WHERE tag = '{$search}')
");