使用联接创建多个表时如何避免出现“模棱两可”的错误消息

时间:2018-10-04 15:57:04

标签: sql postgresql

我正在尝试使用以下代码创建客户及其购买品牌的列表。 brands表具有品牌名称,customer_idcustomers表中。要链接它们,我必须通过brand_id表(连接到receipt_id表)和receipts表(连接到{)将customersreceipt_item_details1链接在一起{1}}表)。

因此,brands表(具有receipt_item_details1列,然后连接到brand_id表)和新表brands(由第一个最里面的子查询创建)正在尝试由customer_receipts链接。在构建连接这两个表的表(原始表:receipt_id和新表:customer_id)时,我想显示receipt_item_details1列。

问题:我一直收到以下错误。如何添加Infix并列出品牌?

  

“列引用“ customer_id”不明确
  第3行:... pts.receipt_id,recease_item_details1.receipt_id,customer_r ..“

customer_receipts

2 个答案:

答案 0 :(得分:2)

您的内部子选择

 (SELECT receipts.customer_id, customers.customer_id

生成一个包含两个名为customer_id的列的结果。因此,如果您引用customer_id

,则下一个较高的子选择在两列之间不会有所不同

您应该给一个或两个别名:

 (SELECT receipts.customer_id as r_customer_id, 
      customers.customer_id as c_customer_id

然后您的下一个更高查询可以致电

 SELECT customer_receipts.c_customer_id...

那么解决问题的第一步:

SELECT 
    customer_brandids.brand_id,                       
    brands.brand_id, 
    customer_brandids.c_customer_id,                    --> reference alias
    brands.brand_name
FROM 
    (SELECT 
         customer_receipts.receipt_id as c_receipt_id,  --> same problem
         receipt_item_details1.receipt_id as r_receipt_id,
         customer_receipts.c_customer_id,               --> reference alias
         receipt_item_details1.brand_id
    FROM
        (SELECT 
             receipts.customer_id as r_customer_id,     --> here was the problem
             customers.customer_id as c_customer_id, 
             receipts.receipt_id
        FROM receipts
        INNER JOIN customers
        ON receipts.customer_id = customers.customer_id) AS customer_receipts
    INNER JOIN receipt_item_details1
    ON customer_receipts.receipt_id = receipt_item_details1.receipt_id) AS customer_brandids
INNER JOIN brands
ON customer_brandids.brand_id = brands.brand_id

附加

  1. 由于receipt_id,您无需同时占用两列(例如,INNER JOIN的两列),从而确保两列的值相同
  2. 您可以使用别名来缩短查询时间。
  3. 您不需要为每个联接创建一个子查询。只需加入即可。

总而言之,这应该做的相同:

SELECT b.brand_id, c.customer_id, b.brand_name 
FROM receipts r
INNER JOIN customers c ON r.customer_id = c.customer_id
INNER JOIN receipt_item_details1 rid ON r.receipt_id = rid.receipt_id
INNER JOIN brands b ON b.brand_id = rid.receipt_id

demo: db<>fiddle

答案 1 :(得分:0)

不要在不需要时使用嵌套选择,尝试使用联接,查询会更简单,看起来像这样

select * from receipts
join customers on receipts.customer_id = customers.customer_id
join receipt_item_details1 on receipts.receipt_id = receipt_item_details1.receipt_id
join brands on receipt_item_details1.brand_id = brands.brand_id

您可以定义要获取的列,而不是星号