由于Ajax调用的结果,我在格式化json对象时遇到了问题,这是我想要的。我也不知道我的方法是否是最好的方法。
为了解释这种情况:假设我有个人的名字和高度,以及他们最喜欢的颜色(可以是几种颜色)存储在我的db中。这些桌子看起来像这样
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-语句以生成正确的格式。
任何一个提示,这将是非常感谢!
谢谢你,帕科
发布于 2016-03-17 21:52:45
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
https://stackoverflow.com/questions/36059289
复制相似问题