使用带有左连接的where子句

时间:2017-02-21 11:37:05

标签: mysql

我有这两个表:

USER:
id  name
1   John
2   Cian
3   Una

ATTR:
id name           value      user_id
1  LAST_LOGGED_IN 2016-10-10 1
1  ADDED          2015-01-01 1
1  ADDED          2015-01-01 2

并希望产生这个:

user_id user_name last_logged_in added 
1       John      2016-10-10     2015-01-01
2       Cian      NULL           2015-01-01
3       Una       NULL           NULL

我的尝试是:

select USER.NAME, ATTR.VALUE as LAST_LOGGED_IN 
from USER 
left join ATTR on USER.ID = ATTR.USER_ID
where ATTR.NAME = "LAST_LOGGED_IN"
GROUP BY USER.NAME;

但这不正确。

1 个答案:

答案 0 :(得分:-1)

select  USER.NAME,  IF(ATTR.NAME = 'LAST_LOGGED_IN',ATTR.VALUE,NULL) as LAST_LOGIN 
from USER 
right join ATTR on USER.ID = ATTR.USER_ID 
GROUP BY USER.ID;