首页 文章

左连接两个表时的不明确的外连接,但链接所有三个时重复记录

提问于
浏览
0

我有三张 table :

Table1 - Customer profile
customer id
customer name
customer country
customer total sales

Table2 - Contract list
contract number
customer id
customer state
contract sales
business code

Table3 - Business index
business code
business type

每个 customer 都有 xxx amount of contractsTable1 中的每个 'customer total sales' 等于该特定客户的 Table2'contract sales' 之和 .

我想列出的是所有客户名称,每个客户的总销售额,国家;还列出每个客户的州和业务类型 .

我的查询试图拉 customer id, customer name, customer country, customer total sales from Table1customer state from Table2business type from Table3 . 但当我左连接Table1.customer id - > Table2.customer id,并且左连接Table2.business代码 - > Table3.business类型时,它会提取我想要的所有数据,但每个客户都有xxx行重复记录 .

然后,我尝试通过删除一个连接并更改连接属性来找出导致它的原因 . 它会弹出 'ambiguous outer join' 的消息:

  • 我删除了其中一个连接,只留下两个与一个Left连接相关联的表;

  • 我将其中一个连接更改为右连接或内连接

1 回答

  • 0

    在T-SQL中:由于表 Customer_profileContract_list 都有 customer_idtable alias 应该用于避免模糊列名错误 . 另外要删除重复的记录 Distinct 应该添加关键字 . 以下查询应该有效:

    select distinct cp.customer_id,
           cp.customer_name,
           cp.customer_country,
           cp.customer_total_sales ,
           cl.customer_state,
           bi.business_type 
    from Customer_profile cp
    left join Contract_list cl on cp.customer_id = cl.customer_id 
    left join Business_index bi on bi.business_code = cl.business_code ;
    

相关问题