like and not like in one mysql query

Maurice Kroon picture Maurice Kroon · Jun 15, 2009 · Viewed 74.1k times · Source

I want to do a query containing 'like' and 'not like'.

Current example: i want everything starting with '1|%' but not with '1|6|199|%' or '1|6|200|%'.

Current query:

'SELECT * FROM `links` WHERE `category` LIKE '1|%' NOT LIKE '1|6|199|%','1|6|200|%' ORDER BY `score` DESC LIMIT 9'.

But that doesn't work. Any tips? thx

Answer

Michael Haren picture Michael Haren · Jun 15, 2009

Just add "and category"...

SELECT * FROM links 
WHERE category LIKE '1|%' 
  AND category NOT LIKE '1|6|199|%','1|6|200|%' 
ORDER BY score DESC LIMIT 9

Actually, the comma separated condition is not a syntax I'm familiar with. If that's not working, try this instead:

SELECT * FROM links 
WHERE category LIKE '1|%' 
  AND category NOT LIKE '1|6|199|%'
  AND category NOT LIKE '1|6|200|%' 
ORDER BY score DESC LIMIT 9