如何从MySQL三个表中获取数据?

时间:2013-11-09 12:08:34

标签: mysql sql

我有三个表:产品名称,参数名称和某些产品的参数值:

产品

+-------+-------------+ 
|   id  |  name       |  
+-------+-------------+
|   1   |  A100       |
+-------+-------------+
|   2   |  B250       |
+-------+-------------+

PARAMS

+-------+-------------+ 
|   id  |  name       |  
+-------+-------------+
|   1   |  width      |
+-------+-------------+
|   2   |  color      |
+-------+-------------+

paramsofproducts

+-------+-----------+-----------+-----------+ 
|   id  |  product  |  param    |  value    |
+-------+-----------+-----------+-----------+ 
|   1   |     1     |    1      |   120     |
+-------+-----------+-----------+-----------+  
|   2   |     1     |    2      |  white    |
+-------+-----------+-----------+-----------+ 
|   3   |     2     |    1      |   275     |
+-------+-----------+-----------+-----------+  
|   4   |     2     |    2      |  black    |
+-------+-----------+-----------+-----------+

如何通过一个查询获取此表(所有产品+参数作为列)?我不能用JOIN来做。

+-------+----------+-----------+-----------+ 
|   id  |  name    |  width    |  color    |
+-------+----------+-----------+-----------+ 
|   1   |  A100    |   120     |  white    |
+-------+----------+-----------+-----------+ 
|   2   |  B250    |   275     |  black    |
+-------+----------+-----------+-----------+

1 个答案:

答案 0 :(得分:0)

我无法呈现您想要的结果,但结果中可能有一些JSON可能的解决方法:

SELECT products.id, products.name, CONCAT('[{',GROUP_CONCAT('"',REPLACE(params.name,  '"', '\\"'),'":"', REPLACE(paramsofproducts.value, '"', '\\"'),'"'),'}]') as params
FROM paramsofproducts 
LEFT JOIN products ON products.id = paramsofproducts.product 
LEFT JOIN params ON params.id = paramsofproducts.param
GROUP BY products.name

结果:

id | name | params
1  | A100 | [{"width":"120","color":"white"}]
2  | B250 | [{"width":"275","color":"black"}]

编辑:转义“