且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将MySQL结果集从行转换为列

更新时间:2023-02-11 08:12:39

Mmmm ... EAV.避免使用EAV(entity-attribute_value)的许多原因之一是,它们更难以报告和查询.但是,如果您提前知道了所需的属性,则可以执行以下操作:

Mmmm...EAVs. One of the many reasons to avoid EAVs (entity-attribute_value) is that they are harder to report and query against. However, if the attributes you want are known ahead of time, you can do something like:

Select id
    , Min( Case When name = 'Make' Then attribute_value End ) As Make
    , Min( Case When name = 'Year' Then attribute_value End ) As Year
    , Min( Case When name = 'Type' Then attribute_value End ) As Type
    , Min( Case When name = 'Axles' Then attribute_value End ) As Axles
    , Min( Case When name = 'Size' Then attribute_value End ) As Size
    , Min( Case When name = 'Frame' Then attribute_value End ) As Frame
    , ...
From attributes
Where name In('Make','Year','Type','Axles','Size','Frame',....)
Group By id

现在,MySQL确实具有GROUP_CONCAT,如果允许,您可以将同一属性的多个值连接到一个列表中(例如,如果一个实体可以具有多个Make属性).

Now, MySQL, does have a GROUP_CONCAT which will let you concatenate multiple values for the same attribute into a list if you allow that (e.g. if an entity can have multiple Make attributes).