【问题标题】:Ambiguous outer join when Left join two tables but duplicate records when link all three左连接两个表时不明确的外连接但链接所有三个表时重复记录
【发布时间】:2013-12-09 00:59:48
【问题描述】:

我有三张桌子:

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 contracts,并且Table1 中的每个'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 code-->Table3.business 类型时,它会提取我想要的所有数据,但每个客户都有 xxx 行重复记录。

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

  1. 我删除了其中一个联接,只留下两个表与一个左联接链接;
  2. 我将任一联接更改为右联接或内联接

【问题讨论】:

  • 您使用的是哪个 DBMS?我不确定我是否完全理解您的问题,但听起来您正在寻找full outer join。你能添加一些示例数据和预期的输出吗?
  • 您使用的是什么查询?你在使用分组吗?正如@a_horse_with_no_name 所说,哪个DBMS? MySQL 的行为与 MSSql 或 Oracle 有所不同。您在查询中使用 group by 吗?
  • @user3027035 - 请包括您尝试过的查询。此外,请使用示例起始数据以及为该示例检索到的结果更新您的问题。顺便说一句,除非您有性能问题,否则将“总计”行存储在 Customer 中是在乞求它与来自Contract 的实际总数匹配...
  • 您好 a_horse_with_no_name,我正在使用 MS Access。我得到的结果是 101, ABC, Australia, 200, NSW, RETAIL 101, ABC, Australia, 200, NSW, RETAIL 101, ABC, Australia, 200, NSW, RETAIL 103, EFG, Australia, 300, QLD, INFRASTRUCTURE 103 , EFG, Australia, 300, QLD, INFRASTRUCTURE 105, HIJ, Australia, 450, VIC, TRAINING 105, HIJ, Australia, 450, VIC, TRAINING ... 第一个客户 ABC 有三份合同,第二个和第三个都有二。我想看到的是 101, ABC, Australia, 200, NSW, RETAIL 103, EFG, Australia, 300, QLD, INFRASTRUCTURE 105, HIJ, Australia, 450, VIC, TRAINING

标签: sql ms-access outer-join


【解决方案1】:

在 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 ;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2018-11-06
    • 2014-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多