如何从不同的表中选择相关数据并使用它来显示mysql和php中的趋势?

时间:2016-08-08 18:23:00

标签: php mysql

我有这三个表,表示三个猫系列的各种科目的表现:

CAT1
adm_no eng mat bio che phy
1111    90  87  89  74  92
2222    65  87  54  65  87
3333    96  95  98  58  56
4444    58  28  88  74  85


CAT2
adm_no eng mat bio che phy
1111    40  82  81  79  90
2222    67  88  78  67  84
3333    97  99  95  24  78
4444    82  22  83  76  90


CAT3
adm_no eng mat bio che phy
1111    80  45  86  74  96
2222    95  87  56  65  83
3333    46  97  84  58  87
4444    78  23  80  74  83

我希望每个学生都能获得科目的表现趋势。例如,如果我希望获得eng的性能趋势,那么结果将是这样的:

adm_no CAT1 CAT2 CAT3
1111   90   40   80
2222   65   67   95
3333   96   97   46
4444   58   82   78

我如何使用mysql和php实现这一目标?其次,最重要的是,如果表的数量不是静态的,它将如何实现? (可能是两个甚至四个)。

2 个答案:

答案 0 :(得分:1)

你应该使用tre三个表之间的内连接

select a.adm_no, a.eng as CAT1, b.eng as CAT2, c.eng as CAT3
from table1 as a 
inner join table2 as b on a.adm_no = b.adm_no
inner join table3 as c on a.adm:no = c.adm_no

答案 1 :(得分:1)

我假设你将拥有至少cat1。该查询基本上就是scaisEdge在他的回答中提供的内容。但是,这将让您了解如何使用PHP动态生成它。以下函数将构建可用于获得所需结果的查询。

function buildQuery($subject) {
    $select .= "select `cat1`.adm_no, `cat1`.`$subject` as CAT1";
    $from = ' from cat1';
    $i = 2;
    while (mysql_num_rows(mysql_query("SHOW TABLES LIKE 'cat$i'"))) {
        $table = "cat$i";
        $label = "CAT$i";
        $previousTable = 'cat'.($i-1);
        $select .= ", `$table`.`$subject` as $label";
        $from .= " inner join $table on `$table`.adm_no = `$previousTable`.adm_no ";
        $i++;
    }
    return $select.$from;
}