mjpramos
mjpramos

Reputation: 543

How to build a pivot table from a query regarding 2 tables

I have a 2 MySQL table looking something like this:

table parents

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

table children

+-------+-----------+-----------+-----------+-----------+
| 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    |

I need to output parents name, birthdate, age, number of children, childrens birthdate (all in same column) as

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

My query currently is:

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

How can I get the children birthdates concatenated in a single column?

Upvotes: 1

Views: 26

Answers (1)

mitkosoft
mitkosoft

Reputation: 5316

Use GROUP_CONCAT in your query:

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

Upvotes: 1

Related Questions