我想在我的数据库中搜索并生成如下查询:
$optionArray = explode(' ', $searchExpression);
$query = 'SELECT * FROM tbl_object WHERE tag LIKE "%'.$optionArray[0].'%" OR
tag LIKE "%'.$optionArray[1].'%" OR tag LIKE "%'.$optionArray[2].'%"
OR ...';
executeQuery($query);//Function to execute above query, no matter which function
现在这是我的问题:
有没有办法根据满足的条件数返回记录?
例如,我希望一个满足更多LIKE
条件的对象以更高的优先级检索。
编辑:
当我在MySQL下面执行以下查询时:
SELECT *
FROM `tbl_object`
WHERE tag LIKE '%water%' OR tag LIKE '%melon%'
ORDER BY (tag LIKE '%water%' + tag LIKE '%melon%') DESC
MySQL回复我这个错误:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '+ tag LIKE '%melon%') DESC
答案 0 :(得分:1)
你可以。
'ORDER BY ((tag LIKE "%'.$optionArray[0].'%") +
(tag LIKE "%'.$optionArray[1].'%") +
(tag LIKE "%'.$optionArray[2].'%")) DESC'
它的作用是总结LIKE
子句的值返回值。例如
assume that the value of TAG is Hello.
所以
tag LIKE '%ell%' ==> 1
tag LIKE '%shell%' ==> 0
tag LIKE '%hellos%' ==> 1
tag LIKE '%x%' ==> 0
-------
2 => this value will sorted out.
答案 1 :(得分:1)
MySQL具有将布尔值视为1(对于" true"结果)或0(对于" false")结果的简洁功能。 使用此方法的一种方法是将行正在满足的条件数相加,并根据该顺序排序(为清晰起见,删除了php字符串构建):
SELECT *
FROM (SELECT *,
tag LIKE '%option1%' +
tag LIKE '%option2%' +
... +
tag LIKE '%optionN%' AS num_matches) t
WHERE num_matches > 0
ORDER BY num_matches