我正在尝试使用以下代码创建客户及其购买品牌的列表。 brands
表具有品牌名称,customer_id
在customers
表中。要链接它们,我必须通过brand_id
表(连接到receipt_id
表)和receipts
表(连接到{)将customers
和receipt_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
答案 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
附加:
receipt_id
,您无需同时占用两列(例如,INNER JOIN
的两列),从而确保两列的值相同总而言之,这应该做的相同:
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
答案 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
您可以定义要获取的列,而不是星号