连接两张表并创建新表:基于Customer与Family表的技术需求
First, let's recap the two tables we're working with to make sure we're aligned:
Customer Table
| ID | Name | Supervisor |
|---|---|---|
| C1 | Jenny | 2011-Apr-2 |
| C2 | Jack | 1975-May-8 |
| C3 | May | 1953-Sept-3 |
Family Table
| ID | Name | Cust_id | Status |
|---|---|---|---|
| F1 | James | C1 | Spouse |
| F2 | Charlie | C1 | Child |
| F3 | Jane | C3 | Child |
The core link here is Family.Cust_id which maps directly to Customer.ID—this is our join key to combine the tables.
Option 1: Create a New Table with Inner Join (Only Matching Records)
An inner join will only include rows where a customer has corresponding family records. This means Jack (C2) won't show up in the result since he has no entries in the Family table.
CREATE TABLE CombinedCustomerFamily AS SELECT c.ID AS Customer_ID, c.Name AS Customer_Name, c.Supervisor, f.ID AS Family_Member_ID, f.Name AS Family_Member_Name, f.Status FROM Customer c INNER JOIN Family f ON c.ID = f.Cust_id;
Option 2: Create a New Table with Left Join (Include All Customers)
If you want to keep every customer—even those without family ties—use a left join. Customers without family records will have NULL values in all family-related columns.
CREATE TABLE CombinedCustomerFamily AS SELECT c.ID AS Customer_ID, c.Name AS Customer_Name, c.Supervisor, f.ID AS Family_Member_ID, f.Name AS Family_Member_Name, f.Status FROM Customer c LEFT JOIN Family f ON c.ID = f.Cust_id;
Sample Results
For the inner join, your new table will look like this:
| Customer_ID | Customer_Name | Supervisor | Family_Member_ID | Family_Member_Name | Status |
|---|---|---|---|---|---|
| C1 | Jenny | 2011-Apr-2 | F1 | James | Spouse |
| C1 | Jenny | 2011-Apr-2 | F2 | Charlie | Child |
| C3 | May | 1953-Sept-3 | F3 | Jane | Child |
For the left join, you'll get an extra row for Jack:
| Customer_ID | Customer_Name | Supervisor | Family_Member_ID | Family_Member_Name | Status |
|---|---|---|---|---|---|
| C1 | Jenny | 2011-Apr-2 | F1 | James | Spouse |
| C1 | Jenny | 2011-Apr-2 | F2 | Charlie | Child |
| C2 | Jack | 1975-May-8 | NULL | NULL | NULL |
| C3 | May | 1953-Sept-3 | F3 | Jane | Child |
Quick note: If you're using SQL Server, swap CREATE TABLE ... AS SELECT for SELECT ... INTO CombinedCustomerFamily FROM ...—the logic stays identical, only the syntax changes slightly per database.
内容的提问来源于stack exchange,提问作者new_learner

