使用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中文網其他相關文章!