繁体   English   中英

将另一个表的列中的一行与多行连接起来

[英]Concatenate A Row from columns of another table with multiple row

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

我陷入了困境。 我想将一个表连接到另一个具有外来 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

非常感谢。

祝一切顺利,

使用条件聚合:

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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM