开发者

MySQL - How to pivot NVP?

开发者 https://www.devze.com 2023-03-04 07:28 出处:网络
Say I have a product_attribute table with the following rows: ================================================================

Say I have a product_attribute table with the following rows:

================================================================
| product_attribute_id | product_id | name         | value     |
================================================================
| 1                    | 25         | Author       | John Doe  |
----------------------------------------------------------------
| 2                    | 25         | Author       | Jane Doe  |
----------------------------------------------------------------
| 3                    | 55         | Publisher    | ABC Corp  |
----------------------------------------------------------------
| 4                    | 55         | Release Date | 20100125  |
----------------------------------------------------------------

I'm looking into implementing Solr for full-text searching and I think this开发者_开发技巧 table potentially has important information that should be indexed. So, I think this table needs to be pivoted (using product_id as the pivot point) so I can combine it with other tables that have information that should be indexed.

Questions:

  1. How do I pivot this in MySQL?
  2. I do not know in advance what all the name/value pairs are going to be. Will this be a problem?
  3. Some attributes have identical names (e.g. "Author" in the example above). Will this be a problem?


thats a pretty standard implementation

SELECT
product_id,
GROUP_CONCAT(if(name = 'Author', value, NULL)) AS 'Author',
GROUP_CONCAT(if(name = 'Publisher', value, NULL)) AS 'Publisher',
FROM product_attribute
GROUP BY product_id; 

you have to

select distinct(name) from product_attribute

so you can build the above query but NO it will not work with identical names , GROUP_CONCAT will concat the values .

i ve seen an implementation which adds a column and populates it with increment values so that it can then pivot the table using variables and a counter. but i dont have that in mysql

0

精彩评论

暂无评论...
验证码 换一张
取 消