0

我有 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,如何解决?

4

2 回答 2

1

您可能需要跳过 where 条件:

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

在此处查看小提琴。

于 2013-07-31T07:47:59.633 回答
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
于 2013-07-31T07:38:20.067 回答