从同一列中选择多个值但在不同条件下

时间:2016-07-07 05:39:20

标签: sql

我的表格很糟糕:

id| order_id | meta_key | meta_value
1 | 14 | 'cost'| 100
2 | 14 | 'tax' | 5
3 | 14 | 'sku' | q-1061

我想为表格中的每个订单选择成本,税金,sku,即:

order_id|cost|tax|sku
14 | 100 | 5 | q-1061 

假设每个订单有3行,最快的方法是什么?

2 个答案:

答案 0 :(得分:1)

如果每个属性只能出现一次,则可以使用自联接:

select t1.order_id, 
       t1.meta_value as cost, 
       t2.meta_value as tax, 
       t3.meta_value as sku
from the_table t1 
  join the_table t2 on t1.order_id = t2.order_id and t2.meta_key = 'tax'
  join the_table t3 on t1.order_id = t2.order_id and t2.meta_key = 'sku'
where t1.meta_key = 'cost';

如果您在(meta_key, order_id)上有索引,这应该相当有效。

答案 1 :(得分:0)

也许你想要这个,这是一种透视表的简单方法:

SELECT
    order_id,
    MAX(CASE WHEN meta_key='cost' THEN meat_value END) AS cost,
    MAX(CASE WHEN meta_key='tax' THEN meat_value END) AS tax,
    MAX(CASE WHEN meta_key='sku' THEN meat_value END) AS sku
FROM yourtable
GROUP BY order_id