首页  >  文章  >  数据库  >  如何将三个 MySQL 表中的数据合并到一个新表中?

如何将三个 MySQL 表中的数据合并到一个新表中?

Susan Sarandon
Susan Sarandon原创
2024-11-23 02:03:17880浏览

How to Combine Data from Three MySQL Tables into a New Table?

mySQL:从三个表的数据和列创建新表

问题:

如何创建一个新表,组合从三个现有表中选择的数据,包括字段last_name、来自人员、详细信息和分类表的名字、电子邮件和年龄?

答案:

要实现此目的,您可以使用 3 路 JOIN。

创建一个新表连接:

CREATE TABLE new_table AS
SELECT p.*, d.content AS age
FROM people AS p
JOIN details AS d ON d.person_id = p.id
JOIN taxonomy AS t ON t.id = d.detail_id
WHERE t.taxonomy = 'age';

此查询将创建一个名为 new_table 的新表,其中包含姓氏、名字、电子邮件和年龄列。详细信息表中的 content 字段用于存储年龄信息。

向现有表中插入数据:

如果您已经创建了 new_table,则可以使用以下查询将数据插入其中:

INSERT INTO new_table (id, last_name, first_name, email, age)
SELECT p.id, p.last_name, p.first_name, p.email, d.content AS age
FROM people AS p
JOIN details AS d ON d.person_id = p.id
JOIN taxonomy AS t ON t.id = d.detail_id
WHERE t.taxonomy = 'age';

加入多个属性:

要从其他表检索多个属性(例如年龄、性别、身高),您需要执行额外的联接:

CREATE TABLE new_table AS
SELECT p.*,
       d1.content AS age,
       d2.content AS gender,
       d3.content AS height
FROM people AS p
JOIN details AS d1 ON d1.person_id = p.id AND d1.taxonomy_id = (SELECT id FROM taxonomy WHERE taxonomy = 'age')
JOIN details AS d2 ON d2.person_id = p.id AND d2.taxonomy_id = (SELECT id FROM taxonomy WHERE taxonomy = 'gender')
JOIN details AS d3 ON d3.person_id = p.id AND d3.taxonomy_id = (SELECT id FROM taxonomy WHERE taxonomy = 'height');

以上是如何将三个 MySQL 表中的数据合并到一个新表中?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn