簡體   English   中英

如何從不同的表中選擇相關數據並使用它來顯示 mysql 和 php 中的趨勢?

[英]How do I select related data from different tables and use it to show trend in mysql and php?

我有這三個表,它們代表了三個貓系列在不同科目中的表現:

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 實現這一目標? 其次也是最重要的,如果表的數量不是靜態的,如何實現? (可能是兩個甚至四個)。

你應該在三個表之間使用內連接

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

我假設你至少會有 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM