sql查询返回错误的结果

时间:2016-06-28 09:32:11

标签: mysql sql

为什么此查询返回companyVisible为0的结果,即使我只询问companyVisible值为1的公司?

for/list

3 个答案:

答案 0 :(得分:2)

ANDOR之前,因此您需要添加括号。

SELECT c.companyID, c.companyDescription , c.companyName ,c.copmanyDrastiriotita, c.companyVisible
FROM company c
WHERE c.companyVisible = 1
AND (c.companyDescription LIKE '%Keyword%'
     OR c.companyName LIKE '%Keyword%'
     OR c.copmanyDrastiriotita LIKE '%Keyword%')

答案 1 :(得分:1)

由于OR子句

AND ...OR子句

周围应用括号

使用此

SELECT c.companyID, c.companyDescription , c.companyName ,c.copmanyDrastiriotita, c.companyVisible
FROM company c
WHERE c.companyVisible = 1
AND (c.companyDescription LIKE '%Keyword%'
OR c.companyName LIKE '%Keyword%'
OR c.copmanyDrastiriotita LIKE '%Keyword%')

答案 2 :(得分:0)

使用析取范式:

SELECT c.companyID,
       c.companyDescription, c.companyName, c.copmanyDrastiriotita,
       c.companyVisible
  FROM company c
 WHERE ( c.companyVisible = 1 AND c.companyName LIKE '%Keyword%' )
       OR ( c.companyVisible = 1 AND c.companyDescription LIKE '%Keyword%' )
       OR ( c.companyVisible = 1 AND c.copmanyDrastiriotita LIKE '%Keyword%' )

使用原始运算符(c3可以是VIEW):

SELECT c2.companyID,
       c2.companyDescription, c2.companyName, c2.copmanyDrastiriotita,
       c2.companyVisible
  FROM company c2, (
                    SELECT c1.companyID, c1.companyName AS text_to_search
                      FROM company c1
                    UNION
                    SELECT c.companyID, c.companyDescription AS text_to_search
                      FROM company c1
                    UNION
                    SELECT c1.companyID, c1.copmanyDrastiriotita AS text_to_search
                      FROM company c1
                   ) AS c3 ( companyID, text_to_search )
 WHERE c2.companyVisible = 1
       AND c3.text_to_search LIKE '%Keyword%'