使用另一个表中的数据填充表

时间:2014-04-21 01:25:23

标签: php mysql join

对MySQL很新,并且遇到这个问题很困难。 在我的PHP脚本中坚持不懈。

这是emailQueue表(道歉,无法发布图片):

http://i.imgur.com/5OOyAE9.jpg

这是学生表:

http://i.imgur.com/inA8TUg.jpg

我想从Students表中获取所有CourseID,并将它们添加到各自StudentEmail行中的第1,2,3列等。提前致谢。

2 个答案:

答案 0 :(得分:1)

您可以通过编程方式执行此操作或使用以下内容:

INSERT INTO db.table-destination (c1, c2, c3...)
SELECT a1, a2, a3... FROM db.table-source;

您也可以尝试SELECT INTO

http://dev.mysql.com/doc/refman/5.0/en/ansi-diff-select-into-table.html

答案 1 :(得分:0)

你可以试试这个:

<?php

/* ESTABLISH CONNECTION */

$con=mysqli_connect("YourHost","Username","Password","NameOfYourDatabase");

if(mysqli_connect_errno()){

echo "Error".mysqli_connect_error();
}

$result=mysqli_query($con,"SELECT * FROM Students ORDER BY StudentEmail"); /* USE ORDER BY StudentEmail */
while($row=mysqli_fetch_array($result)){

$courseid=mysqli_real_escape_string($con,$row['CourseID']); /* STORE THE CURRENT COURSE NAME TO $courseid VARIABLE */

if(empty($studentemail)){
   $studentemail=mysqli_real_escape_string($con,$row['StudentEmail']);
   $id=1;
   /* $studentemail VARIABLE PURPOSE IS TO STORE StudentEmail, FOR LATER CONDITION */
}

else {

   if($row['StudentEmail']==$studentemail){ /* IF $studentemail IS THE SAME WITH THE CURRENT StudentEmail ROW, INCREMENT $id */
   $id=$id+1;
   }

   else { /* ELSE, WHERE $studentemail IS NOT THE SAME WITH THE CURRENT StudentEmail ROW, RESTART THE COUNT OF $id BACK TO 1 AND STORE THE NEW StudentEmail INTO $studentemail */
   $studentemail=mysqli_real_escape_string($con,$row['StudentEmail']);
   $id=1;
   }

}

mysqli_query($con,"UPDATE emailQueue SET '$id'='$courseid' WHERE StudentEmail='$studentemail'"); /* UPDATE QUERY */

} /* END OF WHILE LOOP */

?>