我正在尝试执行以下查询MySQL通过此查询,可以获取比赛中汽车的分类,以及这些汽车的驾驶员查询:SELECT * FROM results INNER JOIN cars ON results.idCar = cars.IdINNER JOIN drivers ON cars.id = drivers.idCarWHERE idSesson = 7 ORDER BY classificationASC此查询返回 2 个模型:结果、会话。并返回每辆车的驾驶员列表问题是它返回每个飞行员的结果,也就是说,相同的结果可以出现3次,只是飞行员不同,我想在一个JSONArray使用此查询,我使用此实现 result := structs.Result{} lastResult := structs.Result{} results := []structs.Result{} driver := structs.Driver{} drivers := []structs.Driver{} for rows.Next() { var sesson structs.Sesson var car structs.Car err = rows.Scan(&result.Id, &sesson.Id, &car.Id, &result.Type, &result.Classification, &result.Category, &car.Id, &car.IdTeam, &car.Name, &car.Number, &car.Model, &car.Manufacturer, &car.TyerBrand, &car.CarImage, &driver.Id, &driver.IdCar, &driver.Name, &driver.Age, &driver.DateOfBrith, &driver.Country, &driver.FlagCountry, &driver.Facebook, &driver.Twitter, &driver.Website, &driver.Picture) if err != nil { fmt.Printf("Error in scan") panic(err.Error()) } result.Sesson = sesson result.Car = car drivers = append(drivers, driver) // i stor the drivers in one array // check if end the duplicated, info if (lastResult.Id != 0 && lastResult.Id != result.Id) { results = append(results, lastResult) } // store the last result lastResult = result } // add last result results = append(results, lastResult) // save the drivers in JSONArray in each jsonObject for i := 0; i < len(results); i++ { for j := 0; j < len(drivers); j++ { if (results[i].Car.Id == drivers[j].IdCarro) { results[i].Drivers = append(results[i].Drivers, drivers[j]) } } } // transform data in json jsonData, err := json.Marshal(results) if err != nil { fmt.Printf("error in marsahl") } db.Close() return jsonData这是一个好的实现吗?对于这个问题??
1 回答
手掌心
TA贡献1942条经验 获得超3个赞
您可以做的几件事
修复结果变量的作用域,将其移动到循环内,它不会在其他任何地方使用
无需创建会话和汽车变量,而是直接扫描到结果变量中
使用映射删除嵌套的 for 循环将节省获得线性复杂性的时间
- 1 回答
- 0 关注
- 64 浏览
添加回答
举报
0/150
提交
取消