组连接不同行

时间:2018-12-10 09:50:48

标签: sql mysqli

CHART

查询后,我需要该结果:

name   type   shape
---------------------
name1  type1  shape1
name1  type2  shape1
name1  type3  shape2

我只能思考:

name    shape1Types     shape2Types
-----------------------------------
name1   type1, type2    type3

但是这里说shape1Types是未知列

2 个答案:

答案 0 :(得分:1)

尝试以下情况,如下尝试

   select name, group_concat(case when shape='shape1' then type end) as shape1Types, group_concat(case when shape='shape2' then type end) as shape2Types 
    from table 
    group by name

答案 1 :(得分:0)

在该WHERE子句中别名名称shape1Types和shape2Types未知。
因此,错误。

您可以IN代替其他两个表中的唯一类型,而不必使用JOIN

select 
 t.name, 
 group_concat(shape1.type) as shape1Types, 
 group_concat(shape2.type) as shape2Types 
from table1 t
left join (select type from table2 where shape = 'shape1' group by type) shape1 
  on shape1.type = t.type
left join (select type from table3 where shape = 'shape2' group by type) shape2 
  on shape2.type = t.type
where t.name = 'name1'
-- and (shape1.type is not null or shape2.type is not null)
group by t.name
相关问题