I am in the situation where I need of the following information:
- ID (posts.ID)
- TITLE (posts.title)
- SKU (postmeta.metakey = ‘_sku’) --> value stored in (postmeta.metavalue)
- PRICE (postmeta.metakey= ‘regular_price’) -> value stored in (postmeta.metavalue)
- BRAND (terms.name WHERE term_taxonomy_term.taxonomy=‘product_cat’)
- CATEGORY (terms.name WHERE term_taxonomy_term.taxonomy=‘brand’)
SKU
and PRICE
belongs to the same column "postemeta.metakey" which related values are in the "postemeta.metavalue".
BRAND
and CATEGORY
belongs to the same column "terms.name" but they have different taxonomies defined in "term_taxonomy.taxonomy" and are ('product_brand' and 'product_cat').
Developing the query below I was able to collect all the information except for one that is the BRAND
(terms.name).
SELECT p.ID
, MAX(CASE WHEN pm1.meta_key = '_sku'
THEN pm1.meta_value
ELSE NULL END) AS sku
, p.post_title
, t.name AS product_category
, MAX(CASE WHEN pm1.meta_key = '_price'
THEN pm1.meta_value
ELSE NULL END) AS price
FROM mg_posts p
LEFT JOIN mg_postmeta AS pm1
ON pm1.post_id = p.ID
LEFT JOIN mg_term_relationships AS tr
ON tr.object_id = p.ID
JOIN mg_term_taxonomy AS tt
ON tt.taxonomy = 'product_cat' AND tt.term_taxonomy_id = tr.term_taxonomy_id
JOIN mg_terms AS t
ON t.term_id = tt.term_id
WHERE p.post_type IN ('product', 'product_variation')
GROUP BY p.ID, p.post_title
Any help to fix this issue??