简体   繁体   English

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

[英]Get multiple values in one column from SQL query

I have 3 tables. 我有3张桌子。

A table: A桌子:

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

B table: B表:

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

C table: C表:

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       | 

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 SQLFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM