我最近刚搬到 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;
关于mysql - 使用 SQL 创建 WooCommerce 分析报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21840674/