user982124 user982124 - 3 months ago 10
MySQL Question

Select data from 3rd related table

I have a simple Select statement that returns data from 2 MySQL tables which is working well. I now need to return some data from a 3rd related table but not sure how to do this.

Here's my current SQL query:

select
p.order_id,
p.order_item_id,
p.order_item_name,
p.order_item_type,
max(CASE WHEN pm.meta_key = '_product_id' and p.order_item_id = pm.order_item_id THEN pm.meta_value END ) as productID,
CAST(max( CASE WHEN pm.meta_key = '_qty' and p.order_item_id = pm.order_item_id THEN pm.meta_value END ) AS UNSIGNED) as Qty,
CAST(max( CASE WHEN pm.meta_key = '_line_total' and p.order_item_id = pm.order_item_id THEN pm.meta_value END ) AS UNSIGNED) as lineTotal,
CAST(max( CASE WHEN pm.meta_key = '_line_subtotal' and p.order_item_id = pm.order_item_id THEN pm.meta_value END ) AS UNSIGNED) as subtotal

from ocm_woocommerce_order_items p join
ocm_woocommerce_order_itemmeta pm
on p.order_item_id = pm.order_item_id
where order_item_type = 'line_item'


group by p.order_item_id


I have a 3rd table 'ocm_postmeta' which has 4 columns: meta_id, meta_key, meta_value and post_id. I need to retrieve the meta_value from this table for the record where the meta_key = _regular_price where:

ocm_postmeta.post_id = ocm_woocommerce_order_itemmeta.meta_value where ocm_woocommerce_order_itemsmeta.meta_key = '_product_id'

Here's a screenshot showing some records from the ocm_woocommerce_order_itemmeta table:

enter image description here

and here's a screenshot showing some records from the ocm_postmeta table:

enter image description here

I'm trying to get the _regular_price value of 100 as the post_id matches the _product_id meta_key value

Answer

Just add it to your join:

SELECT ...
  ,post.meta_value
FROM ocm_woocommerce_order_items p 
JOIN ocm_woocommerce_order_itemmeta pm 
  ON p.order_item_id = pm.order_item_id
LEFT JOIN ocm_postmeta post 
  ON post.post_id = pm.meta_value AND pm.meta_key = '_product_id'
WHERE order_item_type = 'line_item'

Since you only want to match the entries where the meta_key is 'product_id' you need to use a LEFT JOIN to prevent filtering out all other rows.