0

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:

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?

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

2 回答 2

1

Put m.meta_key = 'level' as the join condition.

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'
于 2013-08-02T03:36:15.520 回答
1

Have you tried providing an ELSE clause to your CASE? And according to your tables p.uid doesn't exist, it should be p.user_id, right?

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. 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
于 2013-08-02T03:39:06.913 回答