如果至少满足一次条件,则将值插入表中

时间:2019-01-25 10:34:55

标签: mysql sql mysql-workbench

我创建了以下DataModel

enter image description here

客户

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");

到目前为止,所有这些都工作正常。


现在,我想根据SpecialCustomers条件用表CustomerOrders中的值填充表WHERE。因此,我尝试了以下代码:

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的{​​{1}}和Paypal都具有顺序,因此分配给CreditCard的{​​{1}}是不是唯一的。

但是,我的目标是在满足至少一次条件的情况下,将每个客户插入表PaymentMethod中。
因此,在上述情况下-如果至少用Customer A付款,则应该将客户插入表SpecialCustomers

要使此功能生效,我需要更改什么代码?

4 个答案:

答案 0 :(得分:1)

我认为您只是在选择中缺少别名:

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

答案 1 :(得分:1)

您必须在插入列和select语句(如果模棱两可)中指定全限定名。提示:在您的from子句中使用别名

答案 2 :(得分:1)

在这里,您只需要指定要插入的IdCustomer,就像完成left join一样,我认为它是来自表customer的IdCustomer:

INSERT INTO test.specialcustomers
 (idCustomer, CustomerName)
SELECT c.idCustomer, c.CustomerName
FROM test.customer c
 LEFT JOIN test.orders o ON tc.idCustomer = o.idCustomer
WHERE o.PaymentMethod ="PayPal";

答案 3 :(得分:0)

在两个表中都

from tkinter import * def printSomething(): inputValue=textBox.get("1.0","end-1c") res=response(inputValue) label = Label(root, text=res) #this creates a new label to the GUI label.pack() root = Tk() button = Button(root, text="Print Me", command=printSomething) button.pack() textBox=Text(root, height=2, width=10) textBox.pack() root.mainloop() 列,因此在选择查询中添加表名。

idCustomer