gpt4 book ai didi

mysql - 如何从关于 2 个表的查询构建数据透视表

转载 作者:行者123 更新时间:2023-11-28 23:36:56 26 4
gpt4 key购买 nike

我有一个 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 |

我需要输出 parent 的姓名、生日、年龄、 child 的数量、 child 的生日(都在同一列中)

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

如何将 child 的生日连接到一个列中?

最佳答案

在查询中使用 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

关于mysql - 如何从关于 2 个表的查询构建数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35513360/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com