sachavdk Posted November 26, 2006 Share Posted November 26, 2006 Hi,I've got a query here:[code]SELECT DISTINCT g.group_id, g.name, g.maxmem maxmem FROM groups g, (SELECT COUNT(* ) num, group_id FROM usergroup GROUP BY group_id) ug WHERE g.group_id NOT IN (ug.group_id);[/code]When I remove the where, it gives me 3 results which is correct with my current rows)When I set the were to [color=blue]g.group_id IN (ug.group_id)[/color], it gives me 2 results (also ok).But when I use NOT IN (like the full query above) it gives me the 3 results as without the where.But it should be 1 result. So where does it go wrong? Quote Link to comment https://forums.phpfreaks.com/topic/28545-not-in-not-working/ Share on other sites More sharing options...
btherl Posted November 27, 2006 Share Posted November 27, 2006 I think you should be joining on the group_id between the groups table and the "ug" subquery, rather than using "NOT IN". That "NOT IN" will only check one single ug.group_id, rather than the whole set.Try:[code=php:0]SELECT DISTINCT g.group_id, g.name, g.maxmem maxmem FROM groups g LEFT JOIN (SELECT COUNT(* ) num, group_id FROM usergroup GROUP BY group_id) ug ON g.group_id = ug.group_idWHERE ug.group_id IS NULL[/code]The reason for "IS NULL" is that it will give you all rows not matching ug, which I think is what you want. IS NOT NULL will give you what you wanted when you did "g.group_id IN (ug.group_id)".Alternatively you can do:[code=php:0]SELECT DISTINCT g.group_id, g.name, g.maxmem maxmem FROM groups gWHERE g.group_id NOT IN (SELECT DISTINCT group_id FROM usergroup);[/code]No need to get the count since you aren't using it.. and no need to select from ug when it doesn't appear in the results. Quote Link to comment https://forums.phpfreaks.com/topic/28545-not-in-not-working/#findComment-130741 Share on other sites More sharing options...
sachavdk Posted November 27, 2006 Author Share Posted November 27, 2006 Guess it's working now :)I'm gonna try it with other combinations.But actually I need that count ;)Not in the query (in my program) but I forgot to do an expression on the field and select it.The SELECT should actually beg.group_id, g.name, CONCAT((g.maxmem-gu.num), '/', g.maxmem) freeplacesBut thx for your help Quote Link to comment https://forums.phpfreaks.com/topic/28545-not-in-not-working/#findComment-130784 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.