March 16, 2012

MySQL WHERE IN ()

Question by netcase

My query is:

SELECT * FROM table WHERE id IN (1,2,3,4);

I use it for usergroups and a user can be in more than one group. but it seems that when a record has multiple id like 1 and 3, mySQL does not return that row.
is there any way to get that row too?

Any help would be appreciated!

Answer by Starx

Your query translates to

SELECT * FROM table WHERE id='1' or id='2' or id='3' or id='4';

It will only return the results that match it.


One way of solving it avoiding the complexity would be, chaning the datatype to SET.
Then you could use, FIND_IN_SET

SELECT * FROM table WHERE FIND_IN_SET('1', id);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!