1

我创建了以下查询,它从 3 个不同的表中提取数据:

    SELECT
    product_searchables_names.class_name AS Class_Name,
    product_searchables_names.label AS Attribute_Label,
    jss_products.extrafield102 AS Attribute1,
    jss_products.extrafield103 AS Attribute2,
    jss_products.extrafield104 AS Attribute3,
    jss_products.extrafield105 AS Attribute4,
    jss_products.extrafield106 AS Attribute5,
    jss_products.extrafield107 AS Attribute6
    FROM
    product_searchables_categories 
    JOIN product_searchables_names ON product_searchables_categories.searchableID = product_searchables_names.ID
    JOIN jss_products ON product_searchables_categories.categoryID = jss_products.categories
    WHERE
    jss_products.productID = '134890'
    ORDER BY
    product_searchables_categories.searchable_order ASC

它以以下格式输出数据

在此处输入图像描述

但我需要这种格式,其中第 1 行从 'Attribute'1 中选择值,从 'Attribute2' 中选择第 2 行等:

http://i50.tinypic.com/308bbcg.jpg

我该怎么做?

提前致谢

4

3 回答 3

1

您可以尝试使用案例语句http://dev.mysql.com/doc/refman/5.1/de/case-statement.html之类的

select
    product_searchables_names.class_name AS Class_Name,
    product_searchables_names.label AS Attribute_Label,
    CASE 
        WHEN product_searchables_names.label = 'Resolution' THEN jss_products.extrafield104
        WHEN product_searchables_names.label = 'Networked?' THEN jss_products.extrafield106
        WHEN ...
    END
from
    product_searchables_categories
...

或使用 class_name 代替 label

于 2013-01-16T13:15:35.583 回答
0

根据您发布的图像,您似乎需要取消透视jss_products表。此过程将获取作为列的值并将其转换为行。

因此,您的查询将与此类似:

SELECT psn.class_name AS Class_Name,
    psn.label AS Attribute_Label,
    jp.Attribute
FROM product_searchables_categories psc
JOIN product_searchables_names psn
    ON psc.searchableID = psn.ID
JOIN
(
    select productID, categories, jp.extrafield102 as Attribute
    from jss_products jp
    union all
    select productID, categories, jp.extrafield103 as Attribute
    from jss_products jp
    union all
    select productID, categories, jp.extrafield104 as Attribute
    from jss_products jp
    union all
    select productID, categories, jp.extrafield105 as Attribute
    from jss_products jp
    union all
    select productID, categories, jp.extrafield106 as Attribute
    from jss_products jp
    union all
    select productID, categories, jp.extrafield107 as Attribute
    from jss_products jp
) jp    
    ON psc.categoryID = jp.categories
WHERE jp.productID = '134890'
ORDER BY psc.searchable_order ASC
于 2013-01-16T14:47:13.110 回答
0

您正在寻找的是一个支点。我知道如何在 Oracle 中做到这一点,但我不相信在 mysql 中有一种简单的方法可以做到这一点。获得结果集后,在代码中执行此操作通常比在 SQL 中容易得多。

这是一篇描述如何使用 CASE 执行此操作的帖子,这类似于 Oracle 方法。

带有 GROUP BY 的 mysql 透视查询结果

于 2013-01-16T13:13:27.677 回答