如何选择一个表的记录并将其用作字段以创建另一个表


How to Select the records of one table and use them as the fields to create another Table

我已经浏览了所有各种建议,但似乎没有一个符合要求。这不是数据透视表。第一张表(Course_table)当然有一个列表,大约1,200。我想创建第二个表 (marksheet_table),它的列是第一个表的行。如何使用第一个表中的记录作为其字段名称在 PHP 和 SQL (MySQL) 中创建marksheet_table,例如。

Course_table    
 |  Subject |   unit    |   staff   |
--------------------------------------------------
 |  Math    |   3       |   Mr James    |   
 |  Econs   |   1       |   Dr Smith    |   
 |  Chem    |   2       |   Mrs Aisha   |       

Marksheet_table    
studentid | Math    |   Econs   |   Chem    |
--------------------------------------------------
10001     | 10      |     20    |     30    |
10045     | 11      |     09    |     45    |

 <?php
  include 'config.php'; 
  mysql_select_db("DB_Subject", $conn);
  $Select_sql = mysql_query(" SELECT DISTINCT subject FROM Course_table");   
        while($row= mysql_fetch_array($Select_sql)) 
        { $CourseCode   = $row["CourseCode"] ;
            $Create_sql = mysql_query(" CREATE TABLE Marksheet_table (  
                                    studentId INT(8) NOT NULL,
                                    $subject DECIMAL(4,2), --Math101
                                    $subject DECIMAL(4,2), --ECO302
                                    $subject DECIMAL(4,2), --CHEM112
                                        ");     
                }
          mysql_fetch_array($Create_sql) ;
        mysql_close($conn); 
   ?>

我同意@jeroen对这个问题的评论。但是,要回答这个问题:

你只需要建立你的sql查询:

<?php
include 'config.php';
mysql_select_db("DB_Subject", $conn);
$Select_sql = mysql_query(" SELECT DISTINCT subject FROM Course_table");
$statement = "CREATE TABLE Marksheet_table ( studentId INT(8) NOT NULL, ";
while ($row = mysql_fetch_array($Select_sql)) {
    $CourseCode = $row["CourseCode"];
    $statement .= $row["subject"] . " DECIMAL(4,2), " ;
}
$statement = rtrim($statement, ',') ;
$statement .= ")" ; 
$Create_sql = mysql_query($statement);
mysql_fetch_array($Create_sql);
mysql_close($conn);
?>