如何从mysql连接而不是4连接接收1行

时间:2015-01-20 13:38:28

标签: mysql sql join

SELECT
    pe.entity_id,
    pev.attribute_id,
    pev.entity_id,
    if(pev.attribute_id='134', pev.value, null) as garantie,
    if(pev.attribute_id='97', pev.value, null) as url,
    if(pev.attribute_id='71', pev.value, null) as nume,
    if(pev.attribute_id='85', pev.value, null) as poza
    FROM
    mg_catalog_product_entity pe,
    mg_catalog_product_entity_varchar pev
    WHERE
    pev.entity_id=pe.entity_id and
    (pev.attribute_id='134' or pev.attribute_id='97'  or pev.attribute_id='71'  or pev.attribute_id='85')

我有这个mysql连接返回4行,如下所示:

value1 null null null 
null value2 null null 
null null value3 null 
null null null value4

为了只收到这样的一行,我必须做些什么?

value1 value2 value3 value4

1 个答案:

答案 0 :(得分:2)

SELECT 
    pe.entity_id,
    max(if(pev.attribute_id='134', pev.value, null)) as garantie,
    max(if(pev.attribute_id='97', pev.value, null)) as url,
    max(if(pev.attribute_id='71', pev.value, null)) as nume,
    max(if(pev.attribute_id='85', pev.value, null)) as poza
FROM
    mg_catalog_product_entity pe
JOIN
    mg_catalog_product_entity_varchar pev
ON 
    pev.entity_id = pe.entity_id
WHERE 
    pev.attribute_id in (134,97,71,85)
GROUP BY 
    pe.entity_id