我已经开发了与WooCommerce相关的应用程序。因此,我必须使用WooCommerce的数据库表。
我陷入了困境。我想将一个表连接到具有多行具有foreign_id的另一个表。
例如:
WooCommerce中有2个表。它们是wp_posts
和wp_postmeta
。
wp_posts
包含下表。
| ID | post_title | post_name
| 1682 | foo | foo
| 1681 | bar | bar
wp_postmeta
包含下表。
| post_id | meta_key | meta_value
| 1682 | _regular_price | 100
| 1682 | _sale_price | 99
| 1681 | _regular_price | 300
| 1681 | _sale_price | 299
我想编写导致下表的SQL查询。
| ID | post_title | post_name | _regular_price | _sale_price |
| 1682 | foo | foo | 100 | 99
| 1681 | bar | bar | 300 | 299
非常感谢您。
万事如意
答案 0 :(得分:2)
使用条件聚合:
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
如果元表每个帖子中有很多行,则可以使用以下where
子句优化查询:
where m.meta_key in ('_regular_price', '_sale_price')