Mysql选择两行一体

时间:2018-05-20 12:45:30

标签: mysql sql

我需要在一行中选择由同一个键分组的其他两个值:

TABLE
attribute_id
entity_id
value

DATA
attribute_id|entity_id|     value
          85|      220|      4740
         257|      220|image1.png 

需要这个结果:

attibute_id 85作为SKU,attribute_id 257作为此结果中的IMAGE:

SKU  | IMAGE
4740 | image1.png

我该怎么做? TIA!

2 个答案:

答案 0 :(得分:0)

我认为这可以满足您的需求:

select ts.entity_id, ts.value as sku, ti.value as image
from t ts join
     t ti
     on ts.entity_id = ti.entity_id and
        ts.attribute_id = 85 and
        ti.attribute_id = 257;

您也可以使用条件聚合解决此问题:

select t.entity_id,
       max(case when t.attribute_id = 85 then t.value end) as sku,
       max(case when t.attribute_id = 257 then t.value end) as image
from t
group by t.entity_id;

答案 1 :(得分:0)

如果您在表格中有attribute_id|entity_id个唯一组合,则无需对数据进行分组,只需像这样加入:

http://sqlfiddle.com/#!9/1b2f60/2

SELECT a.entity_id,
       a.value AS some_attribute1,
       b.value AS image
FROM attribs a
LEFT JOIN attribs b
ON a.entity_id = b.entity_id
   AND b.attribute_id = 257
WHERE a.attribute_id = 85