SQL Select语句不能与'类似'正如所料

时间:2017-01-20 09:40:54

标签: mysql sql database sql-like

以下查询按预期工作,并且不会使用&c;#39;返回数据。标志:

SELECT * 
FROM  `func` 
WHERE  `next_act` < 1484870400
AND  `assigned_to` IS NULL
AND `type` like '%FTTC%'
AND  (`flags` NOT LIKE '%c%' OR `flags` IS NULL)
ORDER BY `priority`, `kci3_date`, `kci3_time` ASC
LIMIT 1

当我添加额外的&#39;不喜欢&#39;它开始返回数据&#39; c&#39;在flags

SELECT * 
FROM  `func` 
WHERE  `next_act` < 1484870400
AND  `assigned_to` IS NULL
AND `type` like '%FTCT%'
AND  (`flags` NOT LIKE '%c%' OR `flags` NOT LIKE 'w' OR `flags` IS NULL)
ORDER BY `priority`, `date`, `time` ASC
LIMIT 1

3 个答案:

答案 0 :(得分:0)

您使用的OR与不相似。

SELECT * 
FROM  `func` 
WHERE  `next_act` < 1484870400
AND  `assigned_to` IS NULL
AND `type` like '%FTCT%'
AND  ((`flags` NOT LIKE '%c%' 
       AND `flags` NOT LIKE 'w' ) -- Should this be '%w%' ?
     OR `flags` IS NULL)
ORDER BY `priority`, `date`, `time` ASC
LIMIT 1

您也可以使用:

SELECT * 
FROM  `func` 
WHERE  `next_act` < 1484870400
AND  `assigned_to` IS NULL
AND `type` like '%FTCT%'
AND  (NOT (`flags` LIKE '%c%' 
       OR `flags` LIKE 'w' ) -- Should this be '%w%' ?
      OR `flags` IS NULL)
ORDER BY `priority`, `date`, `time` ASC
LIMIT 1

说(不像&x; xxx&#39;或者不喜欢&#39; yyy&#39;)意味着&#39; xxx&#39;实际上,它并不像“yyy”那样,所以它会返回值。

答案 1 :(得分:0)

您应该将条件与AND合并,而不是OR。根据你的评论

  

我希望它显示除c,w或NULL

以外的任何标志

你想要这样的东西:

  SELECT * 
    FROM `func` 
   WHERE `next_act` < 1484870400
     AND `assigned_to` IS NULL
     AND `type` like '%FTCT%'
     AND  (`flags` <> 'c' AND 
           `flags` <> 'w' AND 
           `flags` IS NOT NULL)
ORDER BY `priority`, 
         `date`, 
         `time` ASC
   LIMIT 1

请注意NOT中的flags IS NOT NULLflags <> 'w'而不是LIKE ...。您可以将<>合并为单个NOT IN

     ...
   WHERE `next_act` < 1484870400
     AND `assigned_to` IS NULL
     AND `type` like '%FTCT%'
     AND  (`flags` NOT IN ('c', 'w') AND 
           `flags` IS NOT NULL)
     ...

答案 2 :(得分:0)

它返回数据&#39; c&#39;因为你正在使用或运营商

`flags` NOT LIKE '%c%' OR `flags` NOT LIKE 'w`

它将检查此条件和返回行,请更正您的查询