views:

14

answers:

3

Hi There,

I have a MySQL select statement dilemma that has thrown me off course a little. In a certain column I have a category term. This term could look something like 'category' or it could contain multiple CSV's like this: 'category, bank special'.

I need to retrieve all rows containing the term 'bank special' in the comma separated value. Currently I am using the following SQL statement:

SELECT * FROM tblnecklaces WHERE nsubcat REGEXP 'bank special';

Now this works OK, but if I had the category as follows: 'diamond special' for example then the row is still retrieved because the term 'special' in my column seems to be matching up to the term 'bank special' in my REGEXP statement.

How would I go abut checking for the existence of the whole phrase 'bank special' only and not partially matching the words?

Many thanks for your time and help

+1  A: 

The simplest solution is to use the LIKE clause (% is wildcard):

SELECT * FROM tblnecklaces WHERE nsubcat LIKE '%bank special%';

Note that LIKE is also a lot faster than REGEXP.

elusive
And will that check for the existence of ONLY 'bank special' and not 'bank' OR 'special'?
webfac
@webfac: This searches for exact matches for _"bank special"_ (including space), and does not care what is in front or behind (thanks to the wildcard). _"bank"_ and _"special"_ are not going to match.
elusive
@elusive thank you so much for your efforts, your solution is simple, lightweight and effective in my situation. Have yourself a good one.
webfac
+1  A: 

You can prefix the column with comma's, and compare it to the bank special:

SELECT  * 
FROM    tblnecklaces
WHERE   ',' + replace(nsubcat,', ','') + ',' LIKE ',bank special,'

I put in a replace to remove optional space after a comma, because your example has one.

Andomar
@Andomar - While I appreciate your help, the above seems like a very intense solution to a not so complex problem. Elusives answer seems to be a little easier to digest. Thank you anyway
webfac
@webfac: The extra code is there so it works if you have both `special` and `back special` as a category. With a simple `like`, both would match `special`. If that kind of complexity is not needed, you're better off with the simple answer :)
Andomar
@Andomar I disagree, with the answer Elusive gave, if I add the wildcard at the end it checks for ONLY what is in between the wild cards and not either or, so %my check% will no check for 'my' OR 'check' but ONLY 'my check'
webfac
@webfac: but `%special%` would match `bank special`, and `bank special,super special,mega special`
Andomar
@Andomar Correct yes, but I need a simple match of 'bank special' against 'bank special' so I need not worry of a conflict in this case.
webfac
A: 

Not tested but this RegExp should work (LIKE works too but will match items that starts or ends with the same phrase):

SELECT * FROM tblnecklaces WHERE nsubcat REGEXP '(^|, )bank special($|,)';
Keeper