我有一个名为“ cars”的mysql表,在其中存储:“ brand”,“ model”,“ color”。我想要这样的数据:
[
{
brand: "audi",
cars: [
{
"model": "coupe",
"color": "red",
},
{
"model": "a3",
"color": "blue",
},
]
},
{
brand: "renault",
cars: [
{
"model": "modus",
"color": "white",
},
{
"model": "clio",
"color": "green",
},
]
},
...
]
所以,我正在做的是第一个mysql查询,按品牌进行分组,然后迭代结果以获取每个品牌的所有汽车:
const query = "SELECT brand FROM cars GROUP BY brand"
mysql.query(query, values, (err, result) => {
for (let i = 0; i < result.length; i++) {
const query2 = "SELECT model, color FROM cars WHERE brand = ?"
const values2 = [result[i].brand]
mysql.query(query2, values2, (err2, result2) => {
result[i].cars = result2
callback(result)
})
}
})
我正在显示的代码可以正常工作,但是我认为对mysql查询进行迭代并不是一件好事。
我做了很多研究,但我真的不知道该怎么做。
是否可以通过一个单独的mysql查询获得此结果?还是应该从“汽车”表中获取所有行,然后用JS的东西来格式化数据?还是应该继续使用此mysql查询迭代?
谢谢
答案 0 :(得分:0)
您可以执行以下操作:
const carsByBrand=[],brands={};
function find(){
const query = "SELECT model, color FROM cars WHERE brand IN ('renault','bmw')"
mysql.query(query, values, (err, result) => {
/*assuming value to be like: [
{
brand:audi,
"model": "coupe",
"color": "red",
},
]
*/
values.forEach((car)=>{
if(brands[car.brand]){
carsByBrand[brands[car.brand]].cars.push(car)
}else{
let index=carsByBrand.push({
brand:car.brand,
cars:[car]
})
brands[car.brand]=index;
}
})
}
})
}
find()
答案 1 :(得分:0)
类似的事情应该可以解决。但是,它的客户端转换是:
let arr1 = ["a","b","c"]
let arr2 = ["1","2","3"]
function concat(arr1, arr2, atIndex){
for(let i = 0; i < arr2.length; i++){
arr1.splice(atIndex+i, 0, arr2[i]);
}
return arr1;
}
concat(arr1, arr2, 2) // ["a", "b", "1", "2", "3", "c"]
concat(arr1, arr2, 0) // ["1", "2", "3", "a", "b", "c"]
答案 2 :(得分:0)
我们可以使用GROUP_CONCAT
,CONCAT
mysql函数通过单个查询本身来实现。
一旦获得结果,汽车钥匙将为JSON字符串。您可以使用JSON.parse方法进行转换
select brand,CONCAT("[",GROUP_CONCAT(CONCAT("{'model':'",model,"','color':'",color,"'}")),"]") as cars from cars GROUP BY brand;