我有两个大表,产品(500k记录)和store_products(> 3mm记录)。产品是主产品,product_stores是产品的独立位置。
我需要从product_stores运行一个QUERY累计信息并更新相应的产品。
当这是较小的数据集时,我们使用嵌套查询来完成它:
SELECT productid,COUNT(id) as count,MIN(price) as lowprice,MAX(price) as highprice FROM store_products
WHILE (productid){ update product set stores = count, min = lowprice, max = highprice WHERE productid = $productid }
GROUP BY productid
我对嵌套更新相当新,并且不确定如何使用连接和分组来设置多个字段。
结构[截断到相关领域]:
CREATE TABLE product (
product_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
stores INT UNSIGNED NOT NULL DEFAULT '0',
lowprice DECIMAL (6,2) NOT NULL DEFAULT '000.00',
highprice DECIMAL (6,2) NOT NULL DEFAULT '000.00',
PRIMARY KEY (product_id),
KEY stores (stores)
)
CREATE TABLE store_product (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
product_id INT UNSIGNED NOT NULL,
price DECIMAL(7,2) NOT NULL DEFAULT '0.00',
PRIMARY KEY (storeproduct_id),
KEY product_id (product_id)
);
要更新的字段:
答案 0 :(得分:4)
运行单个查询以对此大小的表执行更新可能需要一段时间。无论如何 - 以下应该给你你需要的东西。诀窍是对产品表进行别名,然后使用该别名引用子选择中的产品表。所以:
update product p
set p.lowprice = (select min(price) from store_product sp where sp.product_id = p.product_id),
p.highprice = (select max(price) from store_product sp where sp.product_id = p.product_id),
p.stores = (select count(*) from store_product sp where sp.product_id = p.product_id)
where product_id in (select sp.product_id from store_product sp);
这里的一个问题是,对于store_product表中不存在的行,stores列不会更新为0。为了满足这一需求,您可以在执行全局更新时使用IFNULL:
update product p
set lowprice = ifnull((select min(price) from store_product sp where sp.product_id = p.product_id),0),
highprice = ifnull((select max(price) from store_product sp where sp.product_id = p.product_id),0),
stores = ifnull((select count(*) from store_product sp where sp.product_id = p.product_id),0);
你可能想尝试两种方法,看看哪种方法更快。
希望这有帮助!