mrtkprc :
I have developed an application related WooCommerce. Therefore, I must use WooCommerce's database tables.
I am a stuck at a point. I would like to concatenate a table to another table with multiple row which has foreign_id.
For example:
There are 2 tables in WooCommerce. These are wp_posts
and wp_postmeta
.
The wp_posts
contains following table.
| ID | post_title | post_name
| 1682 | foo | foo
| 1681 | bar | bar
The wp_postmeta
contains following table.
| post_id | meta_key | meta_value
| 1682 | _regular_price | 100
| 1682 | _sale_price | 99
| 1681 | _regular_price | 300
| 1681 | _sale_price | 299
I would like to write sql query which result in following table.
| ID | post_title | post_name | _regular_price | _sale_price |
| 1682 | foo | foo | 100 | 99
| 1681 | bar | bar | 300 | 299
Thank you so much.
All The Best,
GMB :
Use conditional aggregation:
select
p.id,
p.post_title,
p.post_name,
max(case when m.meta_key = '_regular_price' then m.meta_value end) regular_price,
max(case when m.meta_key = '_sale_price' then m.meta_value end) sale_price
from wp_posts p
inner join wp_postmeta m on m.post_id = p.id
group by p.id, p.post_title, p.post_name
If the meta table has a large number of rows per post, you can optimize the query with the following where
clause:
where m.meta_key in ('_regular_price', '_sale_price')
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=298052&siteId=1