Error query value is null when using "CASE WHEN ... THEN" in php mysql? -


i have 2 table

c_users(id, name)         1 | peter         2 | micheal  c_user_meta(user_id, meta_key, meta_value)                1   |  c_user_level |  0                    1   |  last_login   |  2013-07-31 14:33:24                2   |  c_user_level |  1                    2   |  last_login   |  2013-07-30 14:33:24    

and query user last login c_user_level = 0

$sql = " select u.* ,            max(case when m.meta_key = 'c_user_level' m.meta_value end ) level,            max(case when m.meta_key = 'last_login' m.meta_value end ) last_login          c_users u          left join c_usermeta m on m.user_id = u.id          u.id >0           , (case when m.meta_key = 'c_user_level' m.meta_value end) = 0           , (case when m.meta_key = 'last_login' m.meta_value end) not null          group u.id order last_login desc" 

and result:

id  | name | level | last_login 1   | peter| null  | 2013-07-31 14:33:24 

error why level of user_id = 1 null, how fix ?

you need skip condition:

select   u.* ,    max(case when m.meta_key = 'c_user_level' m.meta_value end ) level,    max(case when m.meta_key = 'last_login' m.meta_value end ) last_login   c_users u   left join c_usermeta m on m.user_id = u.id u.id >0 group u.id order last_login desc 

or (depending on after) use having clause, filter aggregated value:

select   u.* ,    max(case when m.meta_key = 'c_user_level' m.meta_value end ) level,    max(case when m.meta_key = 'last_login' m.meta_value end ) last_login   c_users u   left join c_usermeta m on m.user_id = u.id u.id >0 group u.id having level=0 , last_login not null order last_login desc 

please see fiddle here.


Comments

Popular posts from this blog

basic authentication with http post params android -

vb.net - Virtual Keyboard commands -

css - Firefox for ubuntu renders wrong colors -