如何根据有关2个表的查询构建数据透视表

时间:2016-02-19 19:24:16

标签: mysql pivot

我有一个2 MySQL表,看起来像这样:

表父母

+-------+-----------+-----------+
| id    |  name     | birthdate |
+-------+-----------+-----------+
|     1 | Mary      | 1974-05-02|
|     2 | John      | 1970-06-03|
|     4 | James     | 1984-07-04|

表儿童

+-------+-----------+-----------+-----------+-----------+
| id    |  parent   | name      |birthdate  |  gender   |
+-------+-----------+-----------+-----------+-----------+
|     1 | 1         | Sara      |2013-10-22 | female    |
|     2 | 1         | Jack      |2014-05-02 | male      |
|     3 | 1         | Jill      |2015-06-07 | female    |
|     4 | 2         | Sam       |2015-06-07 | male      |
|     5 | 2         | Fred      |2015-06-07 | male      |
|     6 | 3         | Julie     |2015-06-07 | female    |
|     7 | 4         | Megan     |2015-06-07 | female    |

我需要输出父母姓名,出生日期,年龄,子女数,儿童出生日期(均在同一栏中)

+---------+--------------+--------+------------+----------------------------------+
| p.name  |  p.birthdate | p.age  | children   |  birthdates                      |
+---------+--------------+--------+------------+----------------------------------+
| Mary    | 1974-05-02   | 42     |    3       | 2013-10-22,2014-05-02,2015-06-07 |

我的查询目前是:

SELECT p.name, p.birthdate, TIMESTAMPDIFF(YEAR, p.birthdate, CURDATE()) AS age, COUNT(c.id) as numchildren
FROM parents p 
INNER JOIN children c ON p.id = c.parent
GROUP BY p.id

如何让孩子们在一个列中连接生日?

1 个答案:

答案 0 :(得分:1)

在查询中使用GROUP_CONCAT:

SELECT
    p. NAME,
    p.birthdate,
    TIMESTAMPDIFF(YEAR, p.birthdate, CURDATE()) AS age,
    COUNT(c.id) AS numchildren,
    GROUP_CONCAT(c.birthdates) birthdates
FROM
    parents p
INNER JOIN children c ON p.id = c.parent
GROUP BY
    p.id