MySQL有关查询构造的问题。根据属性创建列

问题描述 投票:0回答:1

我已经开始使用MySQL数据库。我必须执行从现有数据库使用java创建XML文件的任务。我已经完成了XML结构,并在文档中插入了一些数据,但是从db获取数据时遇到了问题。此问题描述如下:

products_extra_fields

products_extra_fields_id | products_extra_fields_name
-------------------------|---------------------------
           1             |       cpu
           2             |       hdd
           3             |       diagonal
           4             |       gpu

产品

products_id | products_name | products_quantity  
------------| --------------|-------------------
      1     |  product name |      123
      2     |  product name |      125
      3     |  product name |      12
      4     |  product name |      43

products_to_products_extra_fields

products_id  | products_extra_fields_id | products_extra_fields_value
-------------|--------------------------|---------------------------- 
      3      |            1             |             i7
      2      |            4             |           geforce
      2      |            1             |             i5
      3      |            3             |             15.6

查询结果应类似或类似:

products_id | cpu | diagonal |   gpu   | ...
------------|-----|--------- |---------|----
     3      | i7  |   15.6   | geforce | 
...
...

是否有任何简单的方法来获取这样的数据?我已经加入了一些表,但是我的知识表述太差了,无法进行包含上述结果的查询:

SELECT * FROM products p 
INNER JOIN products_description pd ON pd.products_id = p.products_id 
INNER JOIN products_to_categories ptc ON ptc.products_id = p.products_id 
INNER JOIN categories_description cd ON cd.categories_id = ptc.categories_id 
INNER JOIN manufacturers m ON p.manufacturers_id = m.manufacturers_id 
INNER JOIN products_availability_description pad ON pad.products_availability_id = p.products_availability_id 
INNER JOIN products_availability pa ON pa.products_availability_id = pad.products_availability_id 
WHERE p.products_quantity > 30
java mysql jdbc
1个回答
0
投票

您可以使用条件聚合:

select
    pf.products_id,
    max(case when f.products_extra_fields_name = 'cpu'      then pf.products_extra_fields_value end) cpu,
    max(case when f.products_extra_fields_name = 'diagonal' then pf.products_extra_fields_value end) diagonal,
    max(case when f.products_extra_fields_name = 'gpu'      then pf.products_extra_fields_value end) gpu
from products_to_products_extra_fields pf
inner join products_extra_fields f 
    on e.products_extra_fields_id  = pf.products_extra_fields_id 
group by pf.products_id

注意,此结果不需要携带products表;如果您需要该表中的列(例如产品名称),则可以再添加一个join

© www.soinside.com 2019 - 2024. All rights reserved.