在Json的准备中展平表格

时间:2016-07-21 18:16:09

标签: mysql sql json

也许我已经累了但是这让我感到厌烦。

让我们说我想要压扁这张桌子:

pull request

进入此查询结果:

a_id   a_val  b_id   b_val  c_id   c_val  d_id   d_val
1      a      10     b      100    c      1000   f   
1      a      20     d      200    g      null   null 
2      e      30     h      300    i      null   null   
2      j      40     k      null   null   null   null 
3      l      null   null   null   null   null   null

该表只渲染四个级别(a,b,c,d),因此没有动态sql问题。

现在我通常只使用GROUP_CONCAT(CONCAT(...)),但这不会对现有的Null起作用。也许使用coalesce会以某种方式解决这个问题,但是......我现在觉得很愚蠢......我无法弄明白。

不幸的是,我无法在此安装中使用mysql json服务,因此我需要构建数据。感谢。

2 个答案:

答案 0 :(得分:1)

这里的解决方案可能只是巧妙连接和IFNULL调用的组合。我在黑暗中的镜头:

SELECT a_id, GROUP_CONCAT(CONCAT('(',
    a_id, ':', a_value, ',', 
    IFNULL(b_id, ''), IF(b_id IS NOT NULL, ':', ''), IFNULL(b_val, ''),
    ...repeat for c and d
   ')'
) SEPARATOR ',')
FROM table
GROUP BY a_id;

答案 1 :(得分:1)

select a_id as id,
group_concat(concat(
case isnull(a_id) when true then '' else '(' end,
coalesce(a_id, ''),
case isnull(a_id) when true then '' else ':' end,
coalesce(a_val, ''),
case isnull(b_id) when true then '' else ',' end,
coalesce(b_id, ''),
case isnull(b_id) when true then '' else ':' end,
coalesce(b_val, ''),
case isnull(c_id) when true then '' else ',' end,
coalesce(c_id, ''),
case isnull(c_id) when true then '' else ':' end,
coalesce(c_val, ''),
case isnull(d_id) when true then '' else ',' end,
coalesce(d_id, ''),
case isnull(d_id) when true then '' else ':' end,
coalesce(d_val,''),
case isnull(a_id) when true then '' else ')' end
) separator ',')
from table
group by a_id;
相关问题