简体   繁体   English

SQL:自动插入另一个表中的值

[英]SQL: Auto insert the a value from another table

I have two tables the first one is "student":我有两张桌子,第一个是“学生”:


    id (PK) "auto_inc"
    student_name
    email

The second one is "bill":第二个是“账单”:


    id (PK) "auto_inc"
    student_id (FK -> id)
    total_balance

I am trying to auto-insert the last 'id' into 'student_id' when I add a new student in the same query.当我在同一个查询中添加一个新学生时,我试图将最后一个 'id' 自动插入到 'student_id' 中。 This is my query to add a new student to the table这是我向表中添加新学生的查询

insert into student (name, major, emailAddress)
   values ( :name, :major, :emailAddress )

For example:例如:

id= 1
student_name= "Mike"
email= "mike@mail.com"

bill table:
id= 1
student_id= 1 "from 'student' table"
total_balance= 100

I do not have much experience with SQL DB, I am recently using it.我对 SQL DB 没有太多经验,我最近在使用它。

I can advice next approach:我可以建议下一个方法:

  1. create table student with unique key email使用唯一的密钥email创建表student
create table student (
  id int primary key auto_increment,
  student_name varchar(255),
  email varchar(255) unique key
);
  1. use next PHP code:使用下一个 PHP 代码:
<?php

$name = "Barry Block";
$email = "barry.b@gmail.com";
$balance = 500;

$student_sql = "
    insert into student (student_name, email)
    values ( :name, :emailAddress )";

$stmt = $pdo->prepare($student_sql);
$stmt->execute([':name'=>$name, ':emailAddress'=>$email]);

$bill_sql = "
    insert into bill (student_id, total_balance)
    select id, :balance from student where email = :emailAddress";

$stmt = $pdo->prepare($bill_sql);
$stmt->execute([':balance'=>$balance, ':emailAddress'=>$email]);

Test MySQL & PHP code online 在线测试 MySQL 和 PHP 代码

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

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