如何"规范化"来自Ajax的json-object调用或改变SQL查询

时间:2016-03-17 11:31:04

标签: mysql ajax join each

我在Ajax-Call中以我想要的方式格式化json-object时遇到问题。此外,我不知道我的方法是否是最好的方式..

解释情况: 让我们说我的人物及其喜欢的颜色(可以是几个)的名称和高度存储在我的数据库中。表格看起来像这样

persons:
+ id |  name  |  height  +
+++++++++++++++++++++++++++
| 1  | peter  |    185    |
| 2  | paul   |    176    |


colors:
+ id |  color  +
++++++++++++++++    
| 1  |  green  |
| 2  |  blue   |
| 3  |  yellow |
| 4  |  red    |


person_color:
+ id | id_person | id_color  +
++++++++++++++++++++++++++++++    
| 1  |     1     |     1     |
| 2  |     1     |     2     |
| 3  |     1     |     3     |
| 4  |     2     |     2     |
| 5  |     2     |     4     |

我通过左键加入表格来获取我需要的数据

SELECT id, name, height, colors.color 
    FROM persons
LEFT JOIN person_color 
    ON persons.id = person_color.id_person
LEFT JOIN colors 
    ON person_color.id_color = color.id

一切正常。

然后我对查询结果进行json_encode并将对象交还给脚本。

如果调用成功,我会通过像这样

返回返回的对象来创建一个html表
var html = "<table>";
$.each(msg) = function(key, val) { 
   html += "<tr>";
   $.each(val) = function(key2, val2){
      html += "<td>+val2+</td>";
   }
   html += "</tr>";
}
html += "</table>";

这给了我这张桌子的结果:

+ id |  name  |  groesse  |    farbe    +
+++++++++++++++++++++++++++++++++++++++++
| 1  | peter  |    185    |    green    |
| 1  | peter  |    185    |     blue    |
| 1  | peter  |    185    |    yellow   |
| 2  | paul   |    176    |     blue    |
| 2  | paul   |    176    |     red     |

到目前为止,这么好。但我想要实现的是以这样的形式显示结果:

+ id +  name  +  height   +          color          +
+++++++++++++++++++++++++++++++++++++++++++++++++++++    
| 1  | peter  |    185    |   green, blue, yellow   |
| 2  | paul   |    176    |         blue, red       |

不应该太困难,但我要进入圈子......

此外,我不确定是否要更改创建html表的脚本,或者是否有一种聪明的方法来更改SQL语句以生成正确形式的内容。

任何提示都会受到高度赞赏!

提前致谢, 帕

1 个答案:

答案 0 :(得分:0)

mysql中有GROUP_CONCAT聚合函数:

SELECT id, name, height, GROUP_CONCAT(colors.color SEPARATOR ', ') as color
    FROM persons
LEFT JOIN person_color 
    ON persons.id = person_color.id_person
LEFT JOIN colors 
    ON person_color.id_color = color.id
GROUP BY id