我有1个用户表,如下所示:
id name email status
---------------------------------
1 Jane j@ne.do active
2 Jack j@ck.do active
3 Jane j@ne.do inactive
4 Jack j@ck.do inactive
我也有这样的数据表:
id user_id key value
------------------------------
1 1 firts_name Jane
2 1 last_name Do
3 2 city Amsterdam
4 2 first_name Jack
现在我希望在一个查询中让它们像这样:
id name email status firts_name last_name city
-------------------------------------------------------------------------
1 Jane j@ne.do active Jane Do NULL
2 Jack j@ck.do active Jack NULL Amsterdam
3 Jane j@ne.do inactive NULL NULL NULL
4 Jack j@ck.do inactive NULL NULL NULL
甚至可以在一个查询中使用吗?
Normaly我做2个查询,然后在php中结合2但我很好奇是否可能。
答案 0 :(得分:3)
通过连接表并使用CASE
语句,可以非常轻松地完成此操作:
select
u.id,
u.name,
u.email,
u.status,
max(case when a.`key`='first_name' then a.value end) as first_name,
max(case when a.`key`='last_name' then a.value end) as last_name,
max(case when a.`key`='city' then a.value end) as city
from
users u
left join
attr a on a.user_id = u.id
group by
u.id
答案 1 :(得分:0)
答案 2 :(得分:0)
虽然不理想,但相关的子查询可行。类似的东西:
SELECT
`id`,
`name`,
`status`,
(SELECT `value` FROM `table2` WHERE `user_id`=`table1`.`id` AND `key`='first_name') AS first_name,
(SELECT `value` FROM `table2` WHERE `user_id`=`table1`.`id` AND `key`='last_name') AS last_name
FROM `table1`
但是,我觉得有更好的方法来做你想要的。