这是我的代码:
$q = '8gb pro';
$sforeach = explode(' ', $q);
$treffer = "when (titel LIKE '% $q %') then 1";
$sortstring = "";
foreach($sforeach as $sf)
{
$sortstring .= "(titel LIKE '% $sf %') AND";
}
$sortstring = rtrim($sortstring, ' AND');
$sortstring2 = "";
foreach($sforeach as $sf)
{
$sortstring2 .= "(beschreibung LIKE '% $sf %') AND";
}
$sortstring2 = rtrim($sortstring2, ' AND');
$sort = "order by case
$treffer
when $sortstring then 2
when $sortstring2 then 3
else 4
end, views DESC";
当我搜索时,请说8gb pro
,然后title
之类的Acer TravelMate P648-MG-71S5
行显示在标题为Dell Radeon Pro WX 7100 8GB GDDR5
的行之前,即使condidion {{ 1}}应该在when $sortstring then 2
之前出现并将其放在右边?
答案 0 :(得分:0)
也许你想要的排序逻辑是执行多个ORDER BY条件。
在搜索字符串的左侧和右侧添加空格意味着当第一个单词或最后一个单词匹配时,您将无法准确匹配。出于这个原因,我必须敦促你使用较慢的函数REGEXP
及其冗长的单词边界标记。
代码:(Demo)(A basic SQLFiddle Demo)
$q = '8gb pro';
$parts = explode(' ', $q);
$sort = "ORDER BY";
$sort .= " (CASE WHEN `titel` REGEXP '[[:<:]]{$q}[[:>:]]' THEN 1 ELSE 2 END),";
$sort .= " (CASE WHEN `titel` REGEXP '[[:<:]]" . implode("[[:>:]]' AND `titel` LIKE '[[:<:]]", $parts) . "[[:>:]]' THEN 1 ELSE 2 END),";
$sort .= " (CASE WHEN `beschreibung` REGEXP '[[:<:]]" . implode("[[:>:]]' AND `beschreibung` LIKE '[[:<:]]", $parts) . "[[:>:]]' THEN 1 ELSE 2 END),";
$sort .= " `views` DESC";
echo $sort;
输出:
ORDER BY
(CASE WHEN `titel` REGEXP '[[:<:]]8gb pro[[:>:]]' THEN 1 ELSE 2 END),
(CASE WHEN `titel` REGEXP '[[:<:]]8gb[[:>:]]' AND `titel` LIKE '[[:<:]]pro[[:>:]]' THEN 1 ELSE 2 END),
(CASE WHEN `beschreibung` REGEXP '[[:<:]]8gb[[:>:]]' AND `beschreibung` LIKE '[[:<:]]pro[[:>:]]' THEN 1 ELSE 2 END),
`views` DESC