使用 MySQL 将多个表中的数据合并到一个新表
问题:
创建一个新的 MySQL 表,它组合了三个现有表中的特定数据和列:人员、分类和详细信息。目标是创建一个包含选定属性(如姓氏、名字、电子邮件和年龄)的表。
所需的表结构:
ID | Last Name | First Name | Age | |
---|---|---|---|---|
1 | Smith | Fred | Fred@.. | 36 |
2 | Jones | Tom | Tom@.. | 29 |
3 | Doe | Jane | Jane@.. | 27 |
解决方案:
要实现此目的,请对三个执行 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';
此查询根据匹配的 ID 组合来自人员、详细信息和分类表的数据。它从连接的表中选择所需的列(id、last_name、first_name、电子邮件和年龄)。
替代方法:
如果您已经创建了 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';
多个属性:
要包含三个表中的多个属性,您可以为每个属性执行单独的 JOIN:
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 JOIN taxonomy AS t1 ON t1.id = d1.detail_id JOIN details AS d2 ON d2.person_id = p.id JOIN taxonomy AS t2 ON t2.id = d2.detail_id JOIN details AS d3 ON d3.person_id = p.id JOIN taxonomy AS t3 ON t3.id = d3.detail_id WHERE t1.taxonomy = 'age' AND t2.taxonomy = 'gender' AND t3.taxonomy = 'height';
通过使用多个 JOIN,您可以合并来自三个表的数据和列各种表格合并为一个综合的新表格。
以上是如何将多个 MySQL 表中的数据合并到一个新表中?的详细内容。更多信息请关注PHP中文网其他相关文章!