简体   繁体   English

如何用一个查询搜索多个词?

[英]How to search for multiple words with one query?

I am trying to make a simple php search using the following query.我正在尝试使用以下查询进行简单的 php 搜索。 This works perfectly however the query only gives results for the first word.这非常有效,但是查询只给出第一个单词的结果。 Would there be a way to get a combined result for all three words using a single query?有没有办法使用单个查询获得所有三个单词的组合结果?

$stmt = $pdo->prepare("SELECT * FROM walldb WHERE (wallname LIKE :searchq1 OR :searchq2 OR :searchq3) LIMIT :stat, :limt");

You need to repeat the expr like val pattern:您需要expr like val模式expr like val重复expr like val

WHERE wallname LIKE :searchq1 OR wallname LIKE :searchq2 OR wallname LIKE :searchq3

What happends with your original code is that it is interpreted as:您的原始代码发生的情况是它被解释为:

WHERE 
    (wallname LIKE :searchq1)
    OR (:searchq2)
    OR (:searchq3)

So basically the last two search terms are evaluated in boolean context, as if they were conditions.所以基本上最后两个搜索词是在布尔上下文中评估的,就好像它们是条件一样。 If one of the search terms starts with 1 , it is evaluated as true (and all rows in the table will be returned);如果搜索词之一以1开头,则将其评估为 true(并且将返回表中的所有行); else if neither starts with 1 , the conditions are false, hence only the first condition comes into play (which is what you are seeing).否则,如果两者都不以1开头,则条件为假,因此只有第一个条件起作用(这就是您所看到的)。

You cannot use OR in the way you show.您不能以您显示的方式使用OR :searchq2 is not a valid where expression. :searchq2不是有效的 where 表达式。 You need to do the following:您需要执行以下操作:

wallname LIKE :searchq1 OR wallname LIKE :searchq2 OR wallname LIKE :searchq3

You might want to consider regular expressions.您可能需要考虑正则表达式。 You could express what you want as:您可以将您想要的表达为:

where wallname regexp concat('^', concat_ws('|', :searchq1, :searchq2, :searchq3), '$')

assuming that the parameters do not have special characters in them.假设参数中没有特殊字符。

However, perhaps you should consider one regular expression.但是,也许您应该考虑一种正则表达式。 Then you could express the condition as:那么你可以将条件表达为:

where allname regexp '^abc|def|ghi$')

If You want to decrease query execution time, use UNION ALL (as many parts to union as 'OR' appearences).如果您想减少查询执行时间,请使用 UNION ALL(要合并的部分与出现“OR”的次数一样多)。 Otherwise (transparent and short script) use all conditions in one line - as above.否则(透明和短脚本)在一行中使用所有条件 - 如上所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM