使用PHP MySQL编写正确的搜索查询

时间:2014-03-04 18:58:43

标签: php mysql

我一直在尝试使用Like关键字在PHP上编写正确的SQL搜索查询,以根据输入的关键字生成有序结果。

这就是我想要实现的目标

如果我搜索“男人思考”,结果应该像

一样

显示符合“Man thinking”--- 1st

的结果

然后显示“Man”--- 2nd

的结果

然后显示“思考”结果---第3次

我使用了Like关键字,如下所示

select * from tablename where description like % Man thinking %

但它只生成随机结果,而不是由我使用的关键字字符串

排序

1 个答案:

答案 0 :(得分:0)

获得所需内容的最基本答案也是使用ORDER BY子句中的条件,如下所示:

SELECT
    *
FROM
    `tablename`
WHERE
    description LIKE '%man thinking%' OR
    description LIKE '%man%' OR
    description LIKE '%thinking%'
ORDER BY
    description LIKE '%man thinking%' DESC,
    description LIKE '%man%' DESC,
    description LIKE '%thinking' DESC

我不知道这种查询的性能开销。