MySQL将多行连接成一行

时间:2011-02-09 14:11:01

标签: mysql stored-procedures concat

我有一个返回多行的查询,如下面的MySQL:

attribute_name  value
----------------------------------------
username          emailuser
domain          mydomain.com

我的要求输出如下:

username       domain
-----------------------------
emailuser     mydomain.com

当前SQL:

    SELECT pa2.attribute_name, upa2.value
      FROM product p

INNER JOIN product_attribute pa ON p.product_id = pa.product_id
       AND pa.attribute_name = 'alias'

INNER JOIN user_product_attribute upa ON pa.product_attribute_id upa.product_attribute_id

INNER JOIN user_product_attribute upa2 ON upa.user_product_id = upa2.user_product_id

INNER JOIN product_attribute pa2 ON pa2.product_attribute_id = upa2.product_attribute_id
    AND pa2.attribute_name
    IN (
    'username', 'domain'
    )

WHERE p.product_name = 'email'
AND upa.value = 'emailalias@domainalias'

我一直在看group_concat,但我认为这是错误的道路..有什么建议吗?

1 个答案:

答案 0 :(得分:2)

group_concat没有错。以下查询会很慢,但对于一个小表,这可能并不重要。

SELECT 
GROUP_CONCAT(IF(`attribute_name`='username', `value`,'')) AS `username`,
GROUP_CONCAT(IF(`attribute_name`='domain', `value`, '')) AS `domain`,
FROM (your old table or the select query)
GROUP BY `attribute_name`