基本上,用户将输入学生ID,名字,姓氏,教师的名字和教师的姓氏。我想获得与老师的名字和姓氏相对应的ID。
这是我的代码:
$get_teacher = mysqli_query($link, "SELECT id FROM teachers WHERE first_name = '$teacher_first_name' AND last_name = '$teacher_last_name'");
$get_teacher_arr = mysqli_fetch_array($get_teacher);
$result = mysqli_query($link, "INSERT INTO students (student_id, first_name, last_name, teacher_id) VALUES ('$student_id', '$first_name', '$last_name', '$get_teacher_arr[0]');");
答案 0 :(得分:1)
在一个查询中执行
INSERT INTO students (student_id, first_name, last_name, teacher_id)
SELECT $student_id, '$first_name', '$last_name', id
FROM teachers
WHERE first_name = '$teacher_first_name'
AND last_name = '$teacher_last_name'
答案 1 :(得分:0)
可以在一个查询中执行此操作:
INSERT INTO students (student_id, first_name, last_name, teacher_id)
SELECT $student_id, t.id, t.first_name, t.last_name
FROM teachers t
WHERE first_name = '$teacher_first_name' AND last_name = '$teacher_last_name';
首先注意:不要使用填充到字符串中的变量。了解如何在查询中使用参数。您正在使用mysqli_,因此这是正确的方法。
第二个注意事项:您也应该包括学生的姓名。您可以使用更新来完成此操作。
第三点:不要在students
表中重复教师的名字。规范化数据库和具有单独实体的关键原因是避免在多个位置存储相同的数据。因此,您的查询应如下所示:
INSERT INTO students (student_id, teacher_id)
SELECT ?, t.id
FROM teachers t
WHERE first_name = ? AND last_name = ?;
然后你可以使用JOIN获取教师的名字。
答案 2 :(得分:0)
查询3表:
SELECT s.first_name,
t.id_tea
FROM (student s
INNER JOIN st_te st ON s.id_stu = st.id_stu)
INNER JOIN teacher t ON st.id_tea = t.id_tea;
3表:
student st-te teacher
id_stu first_name id id_stu id_tea id_tea first_name
1 John 1 1 1 1 Asher
2 Elsa 2 2 2 2 Lea
查询输出:
first_name id_tea
John 1
Elsa 2
数据库和表的所有SQL:
CREATE DATABASE student_teacher;
CREATE TABLE student (id_stu INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(10));
CREATE TABLE teacher (id_tea INT AUTO_INCREMENT PRIMARY KEY, first_name VARCHAR(10));
CREATE TABLE st_te (id int AUTO_INCREMENT PRIMARY KEY, id_stu INT, id_tea INT);