I have a mysql table, named "cars", where I store : "brand", "model", "color". I would like to get the data like this :
[
{
brand: "audi",
cars: [
{
"model": "coupe",
"color": "red",
},
{
"model": "a3",
"color": "blue",
},
]
},
{
brand: "renault",
cars: [
{
"model": "modus",
"color": "white",
},
{
"model": "clio",
"color": "green",
},
]
},
...
]
So, what I'm doing is a first mysql query where I group by brand, then I iterate the result to get all the cars for each brand :
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)
})
}
})
The code that I'm showing is working, but I don't think that doing an iteration for a mysql query is a good thing.
I've done a lot of research, and I don't really know what to do.
Is it possible to get this result with one single mysql query ? Or should I get all rows from the "cars" table and then do JS stuff to format the data ? Or should I continue using this mysql query iteration ?
Thank you
You can do something like:
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()
Something like this should do the trick. Its client side transformation though:
let carArr = []
const query = "SELECT brand, model, color from cars"
mysql.query(query, values, (err, result) => {
for (let i = 0; i < result.length; i++) {
// Get the index of the brand in the carArr array
let brandIndex = carArr.map(c => c.brand).indexOf(result.brand)
// If the brand is not already in carArr, enter a new value for it
if(brandIndex == -1)
carArr.push({"brand": result.brand, "cars": [{"model": result.model, "color": result.color}]})
// If the brand already exists, add the car type to this specific barnd
else
carArr[brandIndex].cars.push({"model": result.model, "color": result.color})
}
})
We can achieve by single query itself by using GROUP_CONCAT
, CONCAT
mysql function. once you got result cars key will JSON string. you can convert by using JSON.parse method
select brand,CONCAT("[",GROUP_CONCAT(CONCAT("{'model':'",model,"','color':'",color,"'}")),"]") as cars from cars GROUP BY brand;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.