我创建了以下 DataModel
:
表客户
INSERT INTO test.customer
(CustomerName, CustomerCountry, RegistrationDate)
VALUES
("Customer A","DE","2015-05-03"),
("Customer B","US","2015-07-25"),
("Customer C","US","2016-02-15"),
("Customer D","DE","2017-09-21"),
("Customer E","AU","2018-12-07");
表格订单
INSERT INTO test.orders
(idCustomer, PaymentMethod, OrderDate)
VALUES
("1","CreditCard","2015-05-04"),
("1","PayPal","2015-11-18"),
("3","PayPal","2017-09-04"),
("2","Invoice","2018-04-30");
到目前为止一切正常。
现在我想根据 WHERE
使用表 Customer
和 Orders
中的值填充表 SpecialCustomers
状况。因此,我尝试了以下代码:
INSERT INTO test.specialcustomers
(idCustomer, CustomerName)
SELECT idCustomer, CustomerName
FROM test.customer
LEFT JOIN test.orders ON test.customer.idCustomer = test.orders.idCustomer
WHERE PaymentMethod ="PayPal";
导致错误的原因:
Error Code: 1052. Column 'idCustomer' in field list is ambiguous
据我所知,问题是 Customer A
同时通过 Paypal
和 CreditCard
下了订单,所以 PaymentMethod分配给
不是唯一的。Customer A
的
但是,我的目标是在至少一次满足条件 时将每个客户插入到表 SpecialCustomers
中。
因此,在上述情况下,如果至少有一个订单是使用 PayPal
支付的,则应将客户插入到表 SpeicalCustomers
中。
我需要在我的代码中更改什么才能使其正常工作?
最佳答案
我认为您只是在选择中缺少别名:
INSERT INTO test.specialcustomers (idCustomer, CustomerName)
SELECT c.idCustomer, c.CustomerName
FROM test.customer c
LEFT JOIN test.orders o
ON c.idCustomer = o.idCustomer
WHERE o.PaymentMethod = 'PayPal';
关于mysql - 如果至少满足一次条件,则将值插入表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54363503/