2014-02-17 125 views
0

我正在查詢中需要更新表。 這是我的選擇查詢:在更新查詢中使用select select子查詢返回的結果

SELECT so.fk_customer, 
IF (((sum(lgg.fk_catalog_attribute_option_global_gender = 1)/count(lgg.fk_catalog_attribute_option_global_gender)) *100 > 60) AND (c.gender='male'), 'Men', 
IF (((sum(lgg.fk_catalog_attribute_option_global_gender = 2)/count(lgg.fk_catalog_attribute_option_global_gender)) *100 > 60) AND (c.gender='female'), 'Women', '')) as calculatedGender 
FROM catalog_attribute_link_global_gender AS lgg 
INNER JOIN catalog_simple AS cs ON cs.fk_catalog_config = lgg.fk_catalog_config 
INNER JOIN sales_order_item AS soi ON soi.sku = cs.sku 
INNER JOIN sales_order AS so ON soi.fk_sales_order = so.id_sales_order 
INNER JOIN customer as c ON c.id_customer = so.fk_customer 
WHERE lgg.fk_catalog_attribute_option_global_gender IN (1,2) 
AND so.created_at BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW() 
GROUP BY so.fk_customer 
HAVING count(lgg.fk_catalog_attribute_option_global_gender) > 2 

我還有一個表,其中有一列fk_customer和列性別,我需要更新表從上面查詢的結果。我需要在相同的查詢中完成它。上面的查詢給了我完美的結果。

+1

你可以用update-join來完成。這裏是一個鏈接:http://stackoverflow.com/questions/15209414/mysql-update-join。讓我知道要更新表的列和上面選擇的查詢需要加入的列? –

回答

0

你將不得不與此查詢作爲合併UPDATE語句:

UPDATE anotherTable A JOIN 
(SELECT so.fk_customer, 
IF (((sum(lgg.fk_catalog_attribute_option_global_gender = 1)/count(lgg.fk_catalog_attribute_option_global_gender)) *100 > 60) 
AND (c.gender='male'), 'Men', 
IF (((sum(lgg.fk_catalog_attribute_option_global_gender = 2)/count(lgg.fk_catalog_attribute_option_global_gender)) *100 > 60) 
AND (c.gender='female'), 'Women', '')) as calculatedGender, 
'ID' 
FROM catalog_attribute_link_global_gender AS lgg 
INNER JOIN catalog_simple AS cs ON cs.fk_catalog_config = lgg.fk_catalog_config 
INNER JOIN sales_order_item AS soi ON soi.sku = cs.sku 
INNER JOIN sales_order AS so ON soi.fk_sales_order = so.id_sales_order 
INNER JOIN customer as c ON c.id_customer = so.fk_customer 
WHERE lgg.fk_catalog_attribute_option_global_gender IN (1,2) 
AND so.created_at BETWEEN DATE_SUB(NOW(), INTERVAL 30 DAY) AND NOW() 
GROUP BY so.fk_customer 
HAVING count(lgg.fk_catalog_attribute_option_global_gender) > 2) B 
ON A.'ID' = B.'ID' 
SET A.fk_customer = B.fk_customer, 
A.gender = B.calculatedGender; 

這將給你提供你找出「ID」欄上,您將加入兩個表A中的期望的結果和B.

+0

謝謝..它的工作。 :) –