我有以下问题。我试图显示一个阶段的总持续时间和锻炼。我还想同时查询存储每次锻炼练习的相关表格,并显示这个阶段有多少练习:
文本输出为:
Phase 1
Duration: 268
Workouts: 6
Exercises: 17
Phase 2
Duration: 245
Workouts: 6
Exercises: 22
等
table rk_workouts
id | phase | workout | duration
1 | 1 | 1 | 45
2 | 1 | 2 | 49
3 | 1 | 3 | 48
4 | 1 | 4 | 41
5 | 1 | 5 | 42
6 | 1 | 6 | 43
7 | 2 | 1 | 41
8 | 2 | 2 | 40
9 | 2 | 3 | 41
10 | 2 | 4 | 40
11 | 2 | 5 | 43
12 | 2 | 6 | 40
13 | 3 | 1 | 45
14 | 3 | 2 | 40
15 | 3 | 3 | 40
16 | 3 | 4 | 43
17 | 3 | 5 | 47
table rk_exercises
id | workout_id | workout_name
1 | 1 | exercise 1
2 | 1 | exercise 2
3 | 1 | exercise 3
4 | 1 | exercise 4
5 | 1 | exercise 5
6 | 1 | exercise 6
7 | 1 | exercise 7
8 | 2 | exercise 1
9 | 2 | exercise 2
10 | 2 | exercise 3
11 | 2 | exercise 4
12 | 2 | exercise 5
13 | 2 | exercise 6
14 | 3 | exercise 1
15 | 3 | exercise 2
16 | 3 | exercise 3
17 | 3 | exercise 4
etc
我正在查询以下内容:
$this->db->qry = "SELECT
a.phase,
SUM(a.duration) as duration,
COUNT(a.workout) as workouts,
COUNT(b.id) as exercises
FROM
rk_workouts a
JOIN
rk_exercises b
ON
a.workout=b.workout_id
WHERE
a.category_id = '".$catid."'
GROUP BY
a.phase
ORDER BY
a.phase ASC";
然后我将结果插入数组:
$rlt = $this->db->_result();
if(count($rlt) > 0){
$new_arr = array();
foreach($rlt as $dta){
$new_arr["Phases"][] = array(
"phase"=>$dta['phase'],
"duration" => $dta['duration'],
"workouts" => $dta['workouts'],
"exercises" => $dta['exercises']
);
}
我的数组输出结果不是我的预期。我想获得以下输出:
{
"Phases": [{
"phase": "1",
"duration": "268",
"workouts": "6",
"exercises": "17"
}]
}
但我得到以下内容:
{
"Phases": [{
"phase": "1",
"duration": "1788",
"workouts": "40",
"exercises": "40"
}]
}
我非常肯定我的查询非常错误,并想知道是否有人可以帮助我或指出我正确的方向。如果需要,我可以提供全表数据。
感谢您的帮助和时间。
答案 0 :(得分:0)
我正在使用的新查询是在运行主查询之前:
$this->db->qry = "SELECT id FROM rk_workouts";
$mainSQL = $this->db->_execute();
$rlt = $this->db->_result();
while ($row = mysqli_fetch_assoc($mainSQL)) {
$this->db->qry = "SELECT COUNT(id) as exercises, workout_id FROM rk_exercises WHERE workout_id = '".$row['id']."' ";
$subSQL = $this->db->_execute();
while ($row = mysqli_fetch_assoc($subSQL)) {
$this->db->qry = "UPDATE rk_workouts SET exercises = '".$row['exercises']."' WHERE id = ".$row['workout_id'];
$this->db->_execute();
}
}
我在rk_workouts表中添加了一个额外的列来存储COUNT(id)的结果。
我的rk_workouts表上的nain查询如下所示:
$this->db->qry = "SELECT phase, SUM(duration) as duration, COUNT(workout) as workouts, SUM(exercises) as exercises FROM rk_workouts WHERE category_id = '".$catid."' GROUP by phase ORDER BY phase ASC";
我的JSON输出结果现在是:
{
"Phases": [
{
"phase": "1",
"duration": "268",
"workouts": "6",
"exercises": "40"
},
{
"phase": "2",
"duration": "245",
"workouts": "6",
"exercises": "39"
},
{
"phase": "3",
"duration": "215",
"workouts": "5",
"exercises": "32"
},
{
"phase": "4",
"duration": "225",
"workouts": "5",
"exercises": "25"
},
{
"phase": "5",
"duration": "138",
"workouts": "3",
"exercises": "24"
},
{
"phase": "6",
"duration": "616",
"workouts": "11",
"exercises": "80"
}
]
}
这正是我的iOS项目所需要的。 感谢所有参与者。