在php mysql中使用“CASE WHEN ... THEN”时,错误查询值为null?

时间:2013-07-31 07:34:23

标签: php mysql

我有2张桌子

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   

查询使用c_user_level = 0

获取用户上次登录
$sql = " SELECT u.* , 
          max(CASE WHEN m.meta_key = 'c_user_level' THEN m.meta_value END ) level, 
          max(CASE WHEN m.meta_key = 'last_login' THEN m.meta_value END ) last_login
         FROM c_users u
         LEFT JOIN c_usermeta AS m ON m.user_id = u.ID
         WHERE u.id >0
          AND (CASE WHEN m.meta_key = 'c_user_level' THEN m.meta_value END) = 0
          AND (CASE WHEN m.meta_key = 'last_login' THEN m.meta_value END) IS NOT NULL
         GROUP BY u.id ORDER BY last_login DESC"

结果:

ID  | name | level | last_login
1   | peter| NULL  | 2013-07-31 14:33:24

错误为什么user_id = 1的级别为NULL,如何解决?

2 个答案:

答案 0 :(得分:1)

你可能需要跳过你的情况:

SELECT
  u.* , 
  max(CASE WHEN m.meta_key = 'c_user_level' THEN m.meta_value END ) level, 
  max(CASE WHEN m.meta_key = 'last_login' THEN m.meta_value END ) last_login
FROM
  c_users u
  LEFT JOIN c_usermeta AS m ON m.user_id = u.ID
WHERE u.id >0
GROUP BY u.id
ORDER BY last_login DESC

或(取决于你所追求的)使用HAVING子句来过滤聚合值:

SELECT
  u.* , 
  max(CASE WHEN m.meta_key = 'c_user_level' THEN m.meta_value END ) level, 
  max(CASE WHEN m.meta_key = 'last_login' THEN m.meta_value END ) last_login
FROM
  c_users u
  LEFT JOIN c_usermeta AS m ON m.user_id = u.ID
WHERE u.id >0
GROUP BY u.id
HAVING level=0 AND last_login IS NOT NULL
ORDER BY last_login DESC

请参阅小提琴here

答案 1 :(得分:0)

Please, provide else part inside of case statement query :
Format : case
            when condition_here  then 
                 true_statemnt 
            else 
               false_statemnt 
            end
===============================
CASE WHEN m.meta_key = 'c_user_level' THEN m.meta_value else 0 END