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

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

我有三张桌子。
A表格:

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

B表格:
id_b | description
-------------------
  1  |      J
  2  |      K
  3  |      W

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

我怎样才能得到这个结果?
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       |

最佳答案

您可以尝试以下操作:

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

关于mysql - 从SQL查询在一列中获取多个值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31210368/

10-09 04:23