группа concat разных строк - PullRequest
       0

группа concat разных строк

0 голосов
/ 10 декабря 2018
name   type   shape
---------------------
name1  type1  shape1
name1  type2  shape1
name1  type3  shape2

после запроса мне нужен этот результат:

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

я могу думать только столько:

select name, group_concat(type) as shape1Types, group_concat(type) as shape2Types 
from table 
where name = 'name1' 
  and shape1Types in (select type from table2 where shape = 'shape1') 
  and shape2Times in (select type from table3 where shape = 'shape2') 
group by name

но здесь говорится, что shape1Types - неизвестный столбец

Ответы [ 2 ]

0 голосов
/ 10 декабря 2018

Псевдонимы shape1Types & shape2Types неизвестны в этом предложении WHERE.
Отсюда и ошибка.

Вместо использования 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
0 голосов
/ 10 декабря 2018

попробуйте, как показано ниже, используя случай, когда

   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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...