我想在我的数据库中搜索,并生成如下查询:
$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%') DESCMySQL回复我这个错误:
#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
发布于 2014-06-17 05:05:16
你可以的。
'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.发布于 2014-06-17 05:07:07
MySQL有一个很好的特性,可以将布尔值作为1s (表示"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_matcheshttps://stackoverflow.com/questions/24256024
复制相似问题