Well, you goofed on your DB design and now you pay the price for it.
First of all IN() isn't at all usable for this. Even if it were, you would want to be using something like
Code:
WHERE 16 IN ( coursearea )
But that's not how IN works. In can *ONLY* find things in a list of values. And you do not *HAVE* a "list".
It may look like a list to human eyes, but to SQL it is only *one* field. It's just a field that HAPPENS to have commas in it. SQL makes no distinction whatsoever about characters *with* field values. You could as well have had 3$16$21 or 3!16!21 and it would be all the same to the database.
The *PROPER* design for this kind of thing is to use a separate table.
Your profileCoursearea table would be defined something like this:
Code:
CREATE TABLE profileCoursearea (
id int REFERENCES profiles(id),
area int REFERENCES coursearea(id) /* or whatever the field name is in the coursearea table */
);
Is it too late to convince you to fix your DB design?
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
If you care, the reason that even *THIS* query works
Code:
SELECT *
FROM profiles
WHERE coursearea IN (3)
Is because MySQL is so "sloppy" (some would say "forgiving").
What happens: Because your IN() expression was a number (that is, the 3), MySQL attempts to convert all your coursearea field values to a number.
In the process, it does its best to convert strings such as '3,16,21' to a number and succeeds in converting '3' before it encounters the comma, which causes a conversion error. Some other DBs might get this far, but then they would stop on that conversion error and report a type mismatch. MySQL ignores the error and accepts what has been converted so far and so indeed finds that, *AS A NUMBER*, the value '3,16,21' is just 3.
As I said sloppy. I think MySQL is way way too forgiving and so it leads many people (yourself included) into believing that their code is okay when, in fact, you find out later (sometimes years later) that it is not.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Yes, I had a sneaking suspicion that this would be the case. The database has been passed on to me to sort and this was my fear. However, it's not too late to change the design and add in a couple more tables (one for the courseareas and one for the relationship).
Whether or not to rebuild the DB is up to you. If it's not used much, and you know you will never have to answer questions such as those I showed you, you can probably get away with leaving it alone.
But if it's used a lot, in the long run you'll find that rebuilding it will pay huge dividends.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.