gpt4 book ai didi

MySQL 条件插入与 insert .. select

转载 作者:行者123 更新时间:2023-11-29 17:54:28 30 4
gpt4 key购买 nike

我有一个电子商务网站,客户可以登录并查看各种产品的价格。每个客户都有自己的价目表,并且可以通过多种方式设置价格(来源)。表格如下:

CREATE TABLE customer_price_list (
customer_price_id int(11) NOT NULL AUTO_INCREMENT,
customer_account_id int(11) NOT NULL,
product_id int(11) DEFAULT NULL,
currency_id int(11) DEFAULT NULL,
customer_price decimal(7,2) DEFAULT NULL,
source enum('TRADE_DEFAULT','TEMPLATE','SAGE','MANUAL') DEFAULT NULL,
PRIMARY KEY (customer_price_id),
KEY customer_account_id (customer_account_id),
KEY product_id (product_id),
KEY currency_id (currency_id),
KEY source (source)
)

仅采用product_id、customer_price 和来源,一个客户的示例数据可能如下所示(使用product_id 字符串仅用于说明):

Prod_1, 10.00, TRADE_DEFAULT 
Prod_2, 20.00, TRADE_DEFAULT
Prod_3, 25.00, MANUAL

还有一个不同的客户:

Prod_1, 7.50, SAGE 
Prod_2, 20.00, TRADE_DEFAULT
Prod_3, 30.00, TRADE_DEFAULT

某商品的基本价格(无折扣)是当来源为 TRADE_DEFAULT 时的价格 - 上面显示这两位客户各有两件商品的 TRADE_DEFAULT 价格,但在一件商品上获得了折扣。

TRADE_DEFAULT 价格是通过导入包含product_id、currency_id 和 customer_price 的 CSV 文件来设置的。在 PHP 中,我循环遍历 CSV 中的所有行并将值绑定(bind)到此查询:

insert into customer_price_list  
(customer_price_id, customer_account_id, product_id, currency_id, customer_price, source)
select 0, customer_account_id, :product_id, :currency_id, :price, 'TRADE_DEFAULT' from customer_account

当 customer_price_list 为空时(对于 CSV 中的所有 Product_id/currency_id 组合),此方法可以正常工作。但是,如果某些客户已经有product_id/currency_id条目,这将导致额外的行(即该客户的产品将有两个或多个价格)

因此,在处理 CSV 时,我想要:

A) 将任何现有 TRADE_DEFAULT 更新为 CSV 中的新值(再次从 CSV 内容循环运行)

update  customer_price_list set customer_price = :price
where currency_id=:currency_id and product_id=:product_id and source ='TRADE_DEFAULT'

B) 如果该客户没有该产品/货币的价格,则插入 TRADE_DEFAULT 价格

insert (ONLY IF NO PRICE OF ANY SOURCE IS THERE) into customer_price_list  
(customer_price_id, customer_account_id, product_id, currency_id, customer_price, source)
select 0, customer_account_id, :product_id, :currency_id, :price, 'TRADE_DEFAULT' from customer_account

这就是我需要帮助的地方。我搜索了条件插入查询,但我只能找到它们在哪里插入一条记录,如下所示:

insert into table1 (user,rating,last_modified)
select 'user1', 1999, NOW() from table1
where not exists (
select * from table1
where last_modified > '2007-04-13 08:52:41'
and user='user1'
) limit 1

但我想为所有客户插入..选择并执行插入(如果需要)。

谢谢。

最佳答案

尝试使用合并:

https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql

这可能对您的情况有所帮助,因为它允许根据条件插入值并更新它们(如果它们已经存在)。

关于MySQL 条件插入与 insert .. select,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48990458/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com