在一个查询中访问3个表

时间:2012-02-23 12:11:45

标签: php mysql

我想将数据从一个表复制到另一个表。如何?

$P_studentnumber=mysql_real_escape_string($_POST['studentnumber']);
$P_subjectcode=mysql_real_escape_string($_POST['subjectcode']);
$P_semester=mysql_real_escape_string($_POST['semester']);

$sql "INSERT units INTO grades (units) FROM subjects WHERE subjectcode='$P_subjectcode'"; //<--THIS IS THE PART THAT I WOULD WANT TO ADD

$sql="INSERT INTO grades (studentnumber,course, subjectcode, semester, instructorname, units) SELECT '$P_studentnumber', course, '$P_subjectcode', '$P_semester','$instructorname', 'units' FROM students WHERE studentnumber='$P_studentnumber'";

3 个答案:

答案 0 :(得分:1)

您可以尝试:

INSERT table1(col1,col2) SELECT col1,col2 FROM table2

答案 1 :(得分:1)

试试这个

INSERT到site_constants_description SELECT site_constants_description_new。* 来自site_constants_description_new,site_language WHERE site_language.site_language_id = site_constants_description_new.site_language_id;

欢呼声

答案 2 :(得分:0)

SELECT...INSERT语句的正确SQL语法是:

INSERT INTO tableA (colA, colB, colC)
SELECT colA, colB, colC
FROM tableB
WHERE colA = 'valueHere' -- this statement here is the condition

您必须记住,列名称(或字段必须相互匹配。如果您要INSERT的列不匹配,您仍然可以INSERT,但您会为此提供ALIAS

INSERT INTO tableA (colA, colB, colC)
SELECT fieldA as colA, fieldB as colB, fieldC as colC
FROM tableB
WHERE fieldA = 'valueHere' -- this statement here is the condition

JOINED表相同:

INSERT INTO tableA (colA, colB, colC)
SELECT tableB.fieldA as colA, tableB.fieldB as colB, tableC.fieldC as colC
FROM tableB INNER JOIN tableC ON tableB.fieldA = tableC.fieldA
WHERE tableC.fieldA = 'valueHere' -- this statement here is the condition