You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

连接两张表并创建新表:基于Customer与Family表的技术需求

Join Customer and Family Tables to Create a New Table

First, let's recap the two tables we're working with to make sure we're aligned:

Customer Table

IDNameSupervisor
C1Jenny2011-Apr-2
C2Jack1975-May-8
C3May1953-Sept-3

Family Table

IDNameCust_idStatus
F1JamesC1Spouse
F2CharlieC1Child
F3JaneC3Child

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_IDCustomer_NameSupervisorFamily_Member_IDFamily_Member_NameStatus
C1Jenny2011-Apr-2F1JamesSpouse
C1Jenny2011-Apr-2F2CharlieChild
C3May1953-Sept-3F3JaneChild

For the left join, you'll get an extra row for Jack:

Customer_IDCustomer_NameSupervisorFamily_Member_IDFamily_Member_NameStatus
C1Jenny2011-Apr-2F1JamesSpouse
C1Jenny2011-Apr-2F2CharlieChild
C2Jack1975-May-8NULLNULLNULL
C3May1953-Sept-3F3JaneChild

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:23:21