将具有多个行的另一个表的列连接成一行

时间:2020-03-14 22:19:18

标签: mysql sql woocommerce group-by pivot

我已经开发了与WooCommerce相关的应用程序。因此,我必须使用WooCommerce的数据库表。

我陷入了困境。我想将一个表连接到具有多行具有foreign_id的另一个表。

例如:

WooCommerce中有2个表。它们是wp_postswp_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

非常感谢您。

万事如意

1 个答案:

答案 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')
相关问题