简体   繁体   English

使用“%”从SQL查询中获得奇怪的结果

[英]get weird results from SQL query using “%”

I tried to get results from my database using SQL but my results do not agree with what i am using as input. 我试图使用SQL从数据库中获取结果,但是结果与我用作输入的内容不一致。 I always gets results from those who contains both integers and characters. 我总是从那些同时包含整数和字符的人那里得到结果。 For example, if i search for "liu" i get a result of "2LK020". 例如,如果我搜索“ liu”,则会得到“ 2LK020”的结果。 I neither cant search with integers and get a correct result... I use: 我既无法使用整数搜索也无法获得正确的结果...我使用:

    $result = queryDatabase(
    "SELECT course_tag, course_name FROM course WHERE course_tag OR course_name LIKE ?",
    array(1 => '%' .$parameters[0]. '%')

is there a problem using "%"? 使用“%”有问题吗? or why do i get this weird answers? 还是为什么我会得到这个奇怪的答案?

Read this: http://dev.mysql.com/doc/refman/5.7/en/operator-precedence.html 阅读此: http : //dev.mysql.com/doc/refman/5.7/en/operator-precedence.html

You're doing the equivalent of 你做的相当于

WHERE course_tag OR (course_name LIKE ?)

which comes to 涉及到

WHERE true/false OR true/false

As long as course_tag isn't an empty string or a null or other "falsey" value, it'll pretty much always evaluate to a true value, and make the entire WHERE clause evaluate to true . 只要course_tag不是空字符串,null或其他“ falsey”值,它几乎总是会评估为true值,并使整个WHERE子句评估为true

You can't test multiple fields against a single LIKE value. 您不能针对单个LIKE值测试多个字段。 That simply doesn't work. 那根本行不通。 You need to test each one individually: 您需要分别测试每个:

WHERE (course_tag LIKE ?) OR (course_name LIKE ?)

However, since you're doing a %...% double-wild card search, you could optimize a bit with 但是,由于您要进行%...%双通配符搜索,因此您可以通过

WHERE CONCAT(course_tag, course_name) LIKE ?

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

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