我刚刚搬到WooCommerce平台,需要在MySQL中构建SQL来运行我自己的分析报告。例如,我需要报告显示过去30天内每个国家/地区的每个sku的总销售数量。 我探索了像' wp_posts',' wp_postmeta'并发现产品和订单中的大多数字段都是基于记录的,而不是基于列的,这使得SQL更具挑战性。
答案 0 :(得分:4)
最后自己构建了SQL。希望它对那些不想使用分析开箱即用解决方案或需要自定义报告的其他WooCommerce用户有用。
SELECT
sku, count(1)
FROM
wp_woocommerce_order_items oi, -- orders table
wp_posts p, -- woocommerce use posts to keep metadata on the order
wp_postmeta pm, -- we use this table to filter the completed orders
wp_postmeta pm1, -- we use this table again for getting the shipping country info
wp_woocommerce_order_itemmeta oim, -- use this table to get product ids from orders
(SELECT p.id as product_id, meta_value as sku FROM wp_posts p, wp_postmeta pm where
post_type='product' and post_status='publish'
and meta_key='_sku'
and p.id=pm.post_id) as sku_table -- building temp sku table from published products that defines relationship between product id and sku
WHERE
oim.meta_value=sku_table.product_id AND
oi.order_id=p.ID AND
p.id=pm.post_id AND
pm.meta_key='_paid_date' AND -- here we make sure that the order was completed
p.id=pm1.post_id AND
order_item_type='line_item' AND -- get only line items but not tax or shipping
oi.order_item_id=oim.order_item_id AND
oim.meta_key='_product_id' AND
post_date>'2014-01-01' AND -- limits the report date
pm1.meta_key='_shipping_country' AND -- get shipping country
pm1.meta_value='US' -- limits the country
GROUP BY sku
ORDER BY sku;
答案 1 :(得分:0)
如果我错了,请纠正我,但我认为您没有注意到每个订单项在 wp_woocommerce_order_itemmeta
中也有一个数量。因此,您的查询只是计算每个 SKU 的订单数量,而不是销售数量。