我有一个名为Enrollment的数据库,其中所有学生都将添加批处理和课程。 stud_id
,course_id
和batch_id
指的是带有fk的另一个表。
enrolment
+----------+---------+-----------+----------+
| enrol_id | stud_id | course_id | batch_id |
+----------+---------+-----------+----------+
| 1 | 1 | 2 | 1 |
| 2 | 5 | 3 | 2 |
| 3 | 4 | 5 | 3 |
+----------+---------+-----------+----------+
在我删除student
表中的学生记录之前,我想将stud_id
表格中的students
与stud_id
中的enrollment
进行比较表。如果匹配,请不要删除学生。或者某种消息说这条记录与登记表或其他东西相关联。
如果匹配,我想运行此$sql = "DELETE FROM students WHERE student_id = $id ";
students
+---------+------------+-----------+
| stud_id | first_name | last_name |
+---------+------------+-----------+
| 1 | John | Doe |
| 2 | Susy | Roberts |
| 3 | John | redneck |
+---------+------------+-----------+
请帮助!!
答案 0 :(得分:2)
可以使用NOT IN
DELETE FROM students
WHERE student_id NOT IN (SELECT stud_id
FROM enrolment) AND student_id = $id
可以使用NOT EXISTS
DELETE FROM students
WHERE NOT EXISTS(SELECT NULL
FROM enrolment
WHERE stud_id = $id) AND student_id = $id
答案 1 :(得分:1)
您想要运行类似
的查询$sql = SELECT COUNT(1) FROM enrolment WHERE stu_id = $id
然后检查内容以获取返回的数字> 0然后错误。