【问题标题】:Insert value into table if conidition is met at least one time如果条件至少满足一次,则将值插入表中
【发布时间】:2019-01-25 10:34:55
【问题描述】:

我创建了以下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 条件用表CustomerOrders 中的值填充表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 有一个带有PaypalCreditCard 的订单,所以分配给PaymentMethodPaymentMethod 不是唯一的。

但是,我的目标是在至少满足一次条件时将每个客户插入表SpecialCustomers
因此,在上述情况下,如果至少有一个订单使用PayPal 支付,则应将客户插入到表中SpeicalCustomers

我需要对我的代码进行哪些更改才能使其正常工作?

【问题讨论】:

    标签: mysql sql mysql-workbench


    【解决方案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';
    

    【讨论】:

      【解决方案2】:

      如果它们不明确,您必须在插入列和选择语句中指定完整的限定名称。提示:在 from 子句中使用别名

      【讨论】:

        【解决方案3】:

        在这里,您只需指定要插入的 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";
        

        【讨论】:

          【解决方案4】:

          idCustomer 列在两个表中,所以在选择查询中添加表名。

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-11-27
            • 2019-03-01
            • 1970-01-01
            • 2011-03-19
            • 2023-04-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多