SQL查询结合

时间:2018-08-16 21:13:39

标签: php sql database

如何使用一个查询获取以下代码的相同数据? 而不使用多个请求。

我不想使用多个数据库请求。

$result = "SELECT classid FROM student_result_history WHERE s_id = 11 GROUP BY class_name";

foreach($result as $row){
  $classid = $row["classid"];
  $result2 = "SELECT term FROM student_result_history WHERE class_name = $classid GROUP BY term";

  foreach($result2 as $row2){
    $term = $row2["term"];
    $result3 = "SELECT subject_name, primary_mark, secondary_mark, practical_mark FROM student_result_history WHERE term = '$term' AND class_name = '$classid' AND s_id = 11";

    foreach($result3 as $row3){
        print_r($row3);
    }   
  } 
}

我想要类似嵌套数组的结果

array(
    array( /*class_name 1*/
        array( /*term 1*/
            'subject_name' => 'abc',
            'secondary_mark' => 12,
            'practical_mark' => 30
        ),
        array( /*term 2*/
            'subject_name' => 'bcd',
            'secondary_mark' => 32,
            'practical_mark' => 20
        )
    ),
    array( /*class_name 2*/
        array( /*term 1*/
            'subject_name' => 'abc',
            'secondary_mark' => 42,
            'practical_mark' => 20
        ),
        array( /*term 2*/
            'subject_name' => 'bcd',
            'secondary_mark' => 32,
            'practical_mark' => 20
        )
    )
)

2 个答案:

答案 0 :(得分:1)

您将无法使用SQL创建嵌套的PHP数组。不管您的查询做什么,它都将返回行,并且您将不得不在PHP中对其进行操作以获取嵌套结构。由于您所需的所有内容都在同一张表中,因此实际上并不需要使查询变得如此复杂。

只需选择所有想要的列而无需分组。

SELECT class_name, term, subject_name, primary_mark, secondary_mark, practical_mark 
FROM student_result_history WHERE s_id = 11

然后在获取结果时在PHP中创建嵌套结构。

while ($row = $query->fetch()) {
    $result[$row['class_name']][$row['term']] = [
        'subject_name' => $row['subject_name'],
        'secondary_mark' => $row['secondary_mark'],
        'practical_mark' => $row['practical_mark']
    ];
}

答案 1 :(得分:0)

您没有说它的哪个数据库版本,所以我假设它实现了CTE(大多数实现)。在这种情况下,应该执行一个简单的查询:

with
c as (
  select classid 
     from student_result_history 
     where s_id = 11 
     group by class_name
),
t as (
  select term 
     from student_result_history t1
     where t1.class_name = c.classid 
     group by t1.term
)
select subject_name, primary_mark, secondary_mark, practical_mark 
  from student_result_history s
  where s.term = t.term 
    and s.class_name = c.classid 
    and s.s_id = 11

此查询的好处是,它需要对现有的SQL查询进行最小的更改。主要是要结合您拥有的SQL部分。