从SQL查询中获取一列中的多个值

时间:2020-12-18 23:48:40

I have 3 tables.

我有3张桌子。

A table:

id_a | description
-------------------
  1  |      X   
  2  |      Y        
  3  |      Z 
  4  |      H 

B table:

id_b | description
-------------------
  1  |      J   
  2  |      K        
  3  |      W 

C table:

id_c | idex_a | idex_b | quantity
----------------------------------
  1  |    1   |   1    |   10 
  2  |    1   |   2    |   32 
  3  |    2   |   3    |   41 
  4  |    1   |   3    |   10 
  5  |    3   |   2    |   24 
  6  |    3   |   3    |   26 

How can I obtain this result?

我怎样才能获得这个结果?

A.id_a | A.description | All B.description, B.quantity IN C WHITH A.id_a = C.idex_a
   1   |       X       | J[10], K[32], W[10]
   2   |       Y       | W[41]
   3   |       Z       | K[24], W[26]
   4   |       H       | 

1 个解决方案

#1


1  

You can try the following:

您可以尝试以下方法:

select a.id_a
      , a.description
      , coalesce( group_concat(distinct concat(b.description, '[', c.quantity, ']') order by b.id_b separator ', ')
                , '') 
from a
left join c on a.id_a = c.idex_a
left join b on b.id_b = c.idex_b
group by a.id_a
       , a.description

SQLFiddle

#1


1  

You can try the following:

您可以尝试以下方法:

select a.id_a
      , a.description
      , coalesce( group_concat(distinct concat(b.description, '[', c.quantity, ']') order by b.id_b separator ', ')
                , '') 
from a
left join c on a.id_a = c.idex_a
left join b on b.id_b = c.idex_b
group by a.id_a
       , a.description

SQLFiddle