简体   繁体   English

INSERT INTO两个不同的表,但具有相同的ID?

[英]INSERT INTO two different tables, but have the same ID?

I have a database of Users and another table for Teachers. 我有一个用户数据库和另一个教师表。 Teachers have all the properties as a user but also an e-mail address. 教师将所有属性都用作用户,但也包含电子邮件地址。 When inserting into the DB how can I insert the info, ensuring that the ID is the same for both? 插入数据库时​​如何插入信息,确保两者的ID相同?

the ID currently is on automatic incrament. 该ID目前处于自动追踪状态。

this is what I have at the moment: 这就是我现在所拥有的:

$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID) 
    VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
    $result=mysql_query($sqlQuery);

$sqlQuery = "INSERT INTO teacher(email) VALUES ('$myEmail')";
$result=mysql_query($sqlQuery);

thank you! 谢谢!

使用MYSQL函数LAST_INSERT_ID()或php mysql http://ro1.php.net/manual/en/function.mysql-insert-id.php

Try this: 试试这个:

$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID) 
    VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
    $result=mysql_query($sqlQuery);

    $id = mysql_insert_id();

$sqlQuery = "INSERT INTO teacher(id, email) VALUES (' $id ','$myEmail')";
$result=mysql_query($sqlQuery);

After the first insert, fetch the last inserted id: 在第一次插入后,获取最后插入的id:

$last_id = mysqli_insert_id(); // or mysql_insert_id() if you're using old code

Or you could expand your second query and use mysql's integrated LAST_INSERT_ID() function: 或者您可以扩展第二个查询并使用mysql的集成LAST_INSERT_ID()函数:

$sqlQuery = "INSERT INTO teacher(id, email) VALUES ((SELECT LAST_INSERT_ID()), '$myEmail')";

why to use separate table for teachers. 为什么要为教师使用单独的表格。 instead, you can have email field with in user table and additional field with flag (T ( for teacher) and U (for user). Default can be a U. This have following Pros. 相反,您可以在用户表中添加电子邮件字段,并在其他字段中添加标记(T(对于教师)和U(对于用户)。默认可以是U.这具有以下优点。

  1. Will Not increase table size as email would be varchar 不会增加表大小,因为电子邮件将是varchar
  2. Remove extra overhead of maintaining two tables. 消除维护两个表的额外开销。
  3. Same Id can be used 可以使用相同的ID

If you want to have that as separate table then answer you selected is good one but make sure last insert id is called in same connection call. 如果你想把它作为单独的表,那么回答你选择的是好的但确保在同一个连接调用中调用最后一个插入id。

Though you can use the LAST_INSERT_ID() function in order to get the last insert id, the best approach in this case is to create a column reference to user id table. 虽然您可以使用LAST_INSERT_ID()函数来获取最后一个插入ID,但在这种情况下,最好的方法是创建对用户ID表的列引用。

teacher

id | user_id | email

So the teacher.id could be anyting, but the user_id column is the real reference to user table. 所以teacher.id可能是任意的,但user_id列是对user表的真正引用。

If you use InnoDB table, you can make the database consistent using Foreign keys 如果使用InnoDB表,则可以使用外键使数据库保持一致

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM