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

标签 mysql sql

我有 3 个表。

一个表:

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/

相关文章:

mysql - 使用 DATE 和 RANGE COLUMNS 进行分区修剪

php - 如何构建相互依赖的多sql插入查询?

php - 消息系统。关于数据库设计的问题

mysql 将插入的数据追加到列

sql - 如何确保我的 SQL varchar 字段是唯一的

sql server : delete all the rows of all the tables

mysql - 根据记录数计算Mysql查询的执行时间

c# - .NET 项目中 SQL 的最佳实践

c# - 无法从数据库获取不同的 NULL

sql - 如何为表中的特定行获取最近的 n 行?