简体   繁体   English

为什么我从此SQL查询中得到错误的结果?

[英]Why am I getting a wrong result from this SQL query?

I am trying to create a simple search script. 我正在尝试创建一个简单的搜索脚本。

So I wrote the following: 所以我写了以下内容:

SELECT *
FROM snm_content
WHERE
    state = 1 AND
    `catid` NOT IN ('15', '23') AND
    `title` LIKE '%test%' OR `introtext` LIKE '%test%' OR `fulltext` LIKE '%test%'

The first check, WHERE state = 1 fails, I get a result with a state of -2 . 第一次检查WHERE state = 1失败,我得到状态为-2的结果。 How can that be? 怎么可能?

This is my result when I use the query in PHPmyadmin: 这是我在PHPmyadmin中使用查询时的结果:

在此处输入图片说明

How can I still get that result when clearly writing state needs to be 1 . 当清楚地写出state1时,我怎么还能得到那个结果。

You need to apply your OR Clauses within parentheses 您需要在括号内套用OR子句

SELECT * FROM snm_content WHERE state = 1 AND `catid` NOT IN ('15', '23') AND 
(`title` LIKE '%test%' OR `introtext` LIKE '%test%' OR `fulltext` LIKE '%test%')

You need parentheses: 您需要括号:

SELECT *
FROM snm_content
WHERE
    state = 1 AND
    catid NOT IN (15, 23) AND
    (title LIKE '%test%' OR introtext LIKE '%test%' OR fulltext LIKE '%test%');

Because of order of operations rules, your current WHERE clause is being interpreted as this: 由于操作规则的顺序,您当前的WHERE子句被解释为:

WHERE
    ((state = 1 AND
    catid NOT IN (15, 23)) AND
    title LIKE '%test%') OR introtext LIKE '%test%' OR fulltext LIKE '%test%';

That is, the title field would have to match the wildcard expression in order for anything to be returned. 也就是说, title字段必须与通配符表达式匹配才能返回任何内容。

By the way, if you are trying to match the literal word test inside these fields, then consider using REGEXP with word boundaries: 顺便说一句,如果您要在这些字段中匹配文字test ,请考虑将REGEXP与单词边界一起使用:

SELECT *
FROM snm_content
WHERE
    state = 1 AND
    catid NOT IN (15, 23) AND
    (title REGEXP '[[:<:]]test[[:>:]]' OR introtext REGEXP '[[:<:]]test[[:>:]]' OR
     fulltext REGEXP '[[:<:]]test[[:>:]]');

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

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