Max*_*ton 3 mysql sql analytics woocommerce
我最近刚转移到WooCommerce平台,需要在MySQL中构建SQL来运行自己的分析报告。例如,我需要显示最近30天内每个国家/地区每个sku的销售总数的报告。我浏览了“ wp_posts”,“ wp_postmeta”之类的表,发现产品和订单中的大多数字段都是基于记录的,而不是基于列的,这使SQL更具挑战性。
最终由我自己构建了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;
Run Code Online (Sandbox Code Playgroud)