2014-07-17 41 views
1

我需要得到所有包含cooking spray的記錄,但只有當它是不是在報價:MySQL查詢相匹配,無引號字符串

cooking spray > 1 
'cooking spray' > 0 
"cooking spray" > 0 

我只是有麻煩的工作了REGEXP。這似乎很接近,但我收到一條消息,指出「重複操作符操作數無效」。

select count(*) 
from recipes r 
where r.ingredient REGEXP '(?<![\'"])cooking spray(?![\'"])' 
+0

你想'烹飪sprayx'計數作爲匹配? –

回答

2

您可以使用此REGEXP值,而不是:

SELECT COUNT(*) 
FROM recipes r 
WHERE r.ingredient REGEXP '(^|[^\'"])cooking spray([^\'"]|$)' 

編輯:
Patrick Q comment,我編輯的正則表達式匹配:

  • cooking spray
  • foo cooking spray
  • cooking spray bar
  • foo cooking spray bar
+0

mmmm ......在'cooking'之前不會需要一些非引號字符,如果有人出現,在'spray'之後還會匹配一個非引號字符? –

+0

我沒有看到你指的是什麼。 – zessx

+0

@PatrickQ你可以添加'?'(可選效果),很確定它會起作用。 – GeriBoss

0

如何使用like

select count(*) 
from recipes r 
where r.ingredient like '%cooking spray%' and 
     r.ingredient not like '%''cooking spray''%' and 
     r.ingredient not like '%"cooking spray""%'; 

我意識到,如果成分包含引用和不引用的表單,這些解決方案都不會起作用。對於這一點,使用replace

select count(*) 
from recipes r 
where replade(replace(r.ingredient, '''cooking spray''', ''), '"cooking spray"', '') like '%cooking spray%' 
0

試試這個(不使用lookarounds):'.*[^"\']cooking spray[^"\'].*'

(PS:zessx也較快,而他的回答處理邊緣的情況下更好)