MySQL:从另一个表中获取行

时间:2016-07-26 20:07:09

标签: mysql

我有以下两个表:

用户:

id  name
1   bob
2   joe
3   paul

财产:

id  user_id type        name
1   1       car         honda
2   1       computer    mac
3   2       car         toyota
4   2       computer    pc
5   2       phone       htc
6   3       car         toyota
7   3       computer    pc
8   3       phone       samsung

我想创建一个查询,以便将其作为输出:

user_id name    car     computer    phone
1       bob     honda   mac 
2       joe     toyota  pc          htc
3       paul    toyota  pc          samsung

我可以在不使用子查询的情况下执行此操作吗?非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:2)

如果修复了类型列表,您可以使用如下查询:

select
  p.user_id,
  u.name,
  max(case when p.type='car' then p.name end) as car,
  max(case when p.type='computer' then p.name end) as computer,
  max(case when p.type='phone' then p.name end) as phone
from
  possesions p inner join users u
  on p.user_id=u.id
group by
  p.user_id,
  u.name

解释:当条件为真时,case when将返回p.name,否则返回null。这里我们按user_id和name进行分组,max()将返回每个组的最大非null值。