tags:

views:

50

answers:

4

What I'm trying is to get all users that don't have a value set for fid = 13 or no value at all in profile_values. I'm guessing this have an easy solution, ...but I just don't see it. Any help or a point in the right direction is greatly appreciated.

(The tables users and profile_values are both from Drupal.)

Simplified values:

uid   name  fid     value
1   user1    1       foo
1   user1    2       foo
2   user2    12      
2   user2    13      1265662514
3   user3    NULL    NULL
4   user4    NULL    NULL

What I was trying:

SELECT u.uid, u.name, pv.fid, pv.value
FROM users u 
LEFT JOIN profile_values pv ON pv.uid = u.uid  
WHERE u.status != 0
AND (pv.fid != 13 OR pv.fid IS NULL) 
GROUP BY u.uid

uid     name      fid     value
1     user1     1       foo
2     user2     12      foo 
3     user3     NULL    NULL
4     user4     NULL    NULL

My problem is user2 which shouldn't be there since it has a value in fid = 13


Thanks for all the unbelievable fast and qualified answers, cheers!

A: 

Maybe try

AND (pv.fid != 13 OR pv.value IS NOT NULL)

?

Your conditions are little unclear:

get all users that don't have a value set for fid = 13 or no value at all in profile_values

This means "get all users with fid equal to something other than 13 AND with some value in profile_values"?

John at CashCommons
and this will select user2 - 12, because 12 != 13 and 12 IS NOT NULL
zerkms
Do they not want user2?
Anthony
Oh sorry, I was looking at the wrong part of the question. Why does user2 show up twice? Not having unique id's is a problem in itself, right?
Anthony
nope, wrong. the first table at question is a parameters table. 1 row per each parameter. so if user have N parameters - he will have N rows in that table. and while selecting if user have fid = 13 then we have to exclude entire user from query result.
zerkms
+1  A: 

WHERE NOT EXISTS (SELECT 1 FROM profile_values pv WHERE pv.uid = u.uid AND pv.fid = 13)

this is actually a slow solution but i cannot realize any other way

zerkms
+1  A: 

You want to add an AND clause: AND u.uid NOT IN (select uid from profile_values where fid=13) as bad_uids

Mike Sherov
this wouldn't work. take a look about my and Anthony discussion below
zerkms
Actually, this seems to work combined with OR (pv.fid = 13 AND pv.value = '') ...unless I'm overlooking something
Borgenk
@Borgenk: why not mine? ;-) have you tried look at this proposal EXPLAIN? ;-)
zerkms
A: 

You want only the profiles where the value is NOT blank and the fid is not 13, right? So that means if both are true OR if either are true, skip those records. So don't group them together and use the OR. Use and:

WHERE 
u.status != 0
AND 
pv.fid != 13 
AND
pv.fid IS NOT NULL 

OR

WHERE 
u.status != 0
AND 
pv.fid IS NOT (13 OR NULL)
Anthony
http://stackoverflow.com/questions/2225622/mysql-query-help-with-selection/2225646#2225646 - look at my comment there
zerkms