简体   繁体   English

在php mysql中使用“case ... when”时错误返回数据为null?

[英]Error return data null when using “case … when” in php mysql?

I have a sample data: 我有一个示例数据:

users(id, name)  
       1 | peter
       ... 
usermeta(user_id, meta_key, meta_value)
            1   |  level   |    10
            1   |  display |    pc 
           ...   
points(user_id, type, point)
           1  |  like  | 5
           2  | comment| 10     
           ...

And mysql: 和mysql:

SELECT u.*, 
(case when m.meta_key = 'level' then m.meta_value end) level , 
p.points AS point
FROM users u
LEFT JOIN points p ON p.user_id = u.id
LEFT JOIN usermeta AS m ON m.user_id = u.id

Result level = NULL, how to fix it? 结果级别= NULL,如何解决?

id | name | level | point
1  | peter| NULL  |  5
1  | peter| 10    |  10

Put m.meta_key = 'level' as the join condition. m.meta_key = 'level'作为连接条件。

SELECT u.*, 
m.meta_value AS level , 
p.points AS point
FROM users u
LEFT JOIN points p ON p.uid = u.id
LEFT JOIN usermeta AS m ON m.user_id = u.id AND m.meta_key = 'level'

Have you tried providing an ELSE clause to your CASE ? 您是否尝试过向CASE提供ELSE条款? And according to your tables p.uid doesn't exist, it should be p.user_id , right? 根据你的表p.uid不存在,它应该是p.user_id ,对吧?

Also, you should use INNER JOIN in this case as you want to retrieve only those cases in which the id field in the users table matches the ones in points and usermeta respectively. 此外,你应该使用INNER JOIN在这种情况下,只要你想检索其中的情况下id在该领域users表格中的匹配pointsusermeta分别。 This should work properly: 这应该正常工作:

SELECT
    u.*, 
    CASE WHEN m.meta_key = 'level' THEN m.meta_value ELSE NULL END AS level, 
    p.points AS point
FROM users u
INNER JOIN points p ON p.user_id = u.id
INNER JOIN usermeta m ON m.user_id = u.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM