简体   繁体   English

SQL转换表 - >将重复属性更改为列

[英]SQL Converting table -> changing repeating attributes into columns

I'm creating a site using WooCommerce and I would like to integrate it with my warehouse. 我正在使用WooCommerce创建一个网站,我想将它与我的仓库集成。

I need to convert a table that looks like that: 我需要转换一个看起来像这样的表:

   ----------------------------
id |post_id| meta_key|meta_value |
   ----------------------------
 1 | 1     |_stock   |1          |
 2 | 1     |_price   |10         |
 3 | 1     |X        |X          |
 4 | 2     |_stock   |2          |
 5 | 2     |_price   |8          |
 6 | 2     |X        |X          |

into: 成:

   -------------------------
   |post id|_stock | _price  |
   -------------------------
   | 1     |1      |10       |
   | 2     |2      |8        |

I tried: 我试过了:

SELECT post_id, meta_value AS stock
FROM wp_postmeta
JOIN
(
SELECT post_id, meta_value AS regular_price
FROM wp_postmeta
WHERE wp_postmeta.meta_key = '_regular_price' 
)
WHERE wp_postmeta.meta_key = '_stock'
ORDER BY post_id ASC

and got: 得到了:

'#1248 - Every derived table must have its own alias '#1248 - 每个派生表必须有自己的别名

Is there any way that avoids create table ? 有什么方法可以避免create table吗?

I've just started my adventure with sql and sorry if the answer is obvious. 我刚开始使用sql进行冒险,如果答案很明显,我很抱歉。 And sorry if the title is misleading. 如果标题具有误导性,那就很抱歉。

Thank You in advance. 先感谢您。

Just use conditional aggregation: 只需使用条件聚合:

select post_id,
       max(case when meta_key = '_stock' then meta_value end) as stock,
       max(case when meta_key = '_regular_price' then meta_value end) as regular_price
from wp_postmeta
where meta_key in ('_stock', '_regular_price')
group by post_id;

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

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