简体   繁体   English

查询返回所有行

[英]Query returns all the rows

Why does this query returns me all the rows matching my OR LIKE condition and jumps over doctorLang . 为什么此查询返回我符合OR LIKE条件的所有行并跳过doctorLang city . city What I mean is I get all the rows in all towns not in only certain one. 我的意思是,我得到的是所有城镇的所有行,而不仅仅是某些行。

SELECT `doctor`.`id`, `doctorLang`.`first_name`, `doctorLang`.`second_name`, `doctorLang`.`city`, `doctorLang`.`hospital_name`
FROM `doctor` LEFT JOIN `doctorLang` ON `doctor`.`id`=`doctorLang`.`doc_id`
WHERE `doctorLang`.`city`='Пловдив' 
AND `doctorLang`.`language`='bg' 
AND `doctor`.`active`=1
AND `doctorLang`.`first_name` LIKE '%йло'
OR `doctorLang`.`first_name` LIKE '%йло%'
OR `doctorLang`.`first_name` LIKE 'йло%'
OR `doctorLang`.`second_name` LIKE '%йло'
OR `doctorLang`.`second_name` LIKE '%йло%'
OR `doctorLang`.`second_name` LIKE 'йло%'
OR `doctorLang`.`third_name` LIKE '%йло'
OR `doctorLang`.`third_name` LIKE '%йло%'

Here is a version of your WHERE clause which should behave as expected: 这是您的WHERE子句的版本,其行为应与预期的一样:

WHERE
    doctorLang.city = 'Пловдив' AND
    doctorLang.language = 'bg'  AND
    doctor.active = 1           AND
    (
        doctorLang.first_name LIKE '%йло'   OR
        doctorLang.first_name LIKE '%йло%'  OR
        doctorLang.first_name LIKE 'йло%'   OR
        doctorLang.second_name LIKE '%йло'  OR
        doctorLang.second_name LIKE '%йло%' OR
        doctorLang.second_name LIKE 'йло%'  OR
        doctorLang.third_name  LIKE '%йло'  OR
        doctorLang.third_name LIKE '%йло%'
    )

Your original WHERE clause, without parentheses, was being interpreted as this: 您原来的WHERE子句(不带括号)被解释为:

WHERE
    (
        doctorLang.city = 'Пловдив' AND
        doctorLang.language = 'bg'  AND
        doctor.active = 1           AND
        doctorLang.first_name LIKE '%йло'
    )
    OR
        doctorLang.first_name LIKE '%йло%'  OR
        doctorLang.first_name LIKE 'йло%'   OR
        ...

In other words, if even one of the OR conditions involving the name were true, it would cause all rows to be returned, apparently ignoring your other restrictions. 换句话说,即使涉及名称的OR条件之一为真,也将导致所有行都被返回,显然会忽略您的其他限制。

The take home lesson here is that AND has higher precedence , or order of execution, than OR . 值得一提的是, AND 优先级或执行顺序比OR更高。 But we can impose any evaluation order we want by using parentheses. 但是我们可以使用括号强加我们想要的任何评估顺序。

It is working for an or condition actually its like city='something' or name='something' 它正在为一个或一个条件工作,实际上是像city ='something'或name ='something'

use a subquery instead 改用子查询

first fetch for the town you are looking for and then from that result for the names you are looking for 首先获取您要查找的城镇,然后从结果中获取您要查找的名称

hope it helps 希望能帮助到你

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

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