为csv导出扁平化多对多关系

时间:2016-03-04 08:30:23

标签: mysql

为了进行csv导出,我要将多对多关系压扁。

我的桌子:

  

用户:

------------
|id | Name |
------------
| 1 | John |
| 2 | Doe  |
  

USER_GROUP:

-------------------
|idUser | idGroup |
-------------------
| 1     | 1       |
| 1     | 2       |
| 2     | 2       |
  

组:

------------
|id | Name |
------------
| 1 | Foo  |
| 2 | Bar  |

我想要一个像这样的输出:

--------------------------------
| Name | Foo group | Bar group |
--------------------------------
| John | x         | x         |
| Doe  |           | x         |

我完全迷失了,不知道我应该做什么,任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

基本的数据透视查询结合几个连接将为您提供所需的结果:

SELECT t.name,
    CASE WHEN SUM(t.FooGroup) > 0 THEN 'x' ELSE '' END AS `Foo group`,
    CASE WHEN SUM(t.BarGroup) > 0 THEN 'x' ELSE '' END AS `Bar group`
FROM
(
    SELECT u.Name,
        CASE WHEN g.Name = 'Foo' THEN 1 ELSE 0 END AS FooGroup,
        CASE WHEN g.Name = 'Bar' THEN 1 ELSE 0 END AS BarGroup
    FROM User u INNER JOIN User_Group ug
        ON u.id = ug.idUser
    INNER JOIN Group g
        ON ug.idGroup = gl.id
) t
GROUP BY t.name