简体   繁体   English

如何设置外键并从多个表中检索或删除数据?

[英]How to set a foreign key and retrieve or delete data from multiple tables?

I am new to php and mysql. 我是php和mysql的新手。 I created a database named 'students' which contain two tables as 'student_details' which have fields like 'ID, Name, Age, Tel#, Address' and another table as 'fee_details' which have fields like 'ID(student_details table ID), Inst Id, Date, Receipt No'. 我创建了一个名为“ students”的数据库,其中包含两个表作为“ student_details”,其中包含“ ID,姓名,年龄,电话号码,地址”等字段,而另一个表则是“ fee_details”,其中包含诸如“ ID(student_details table ID)”等字段,编号,日期,收据编号”。

I want to set a foreign key and retrieve data from both tables when a student paid their fees and if a student passed out or discontinued I want a delete option to delete his all records from my tables. 我想设置一个外键,并在学生支付费用时从两个表中检索数据,并且如果学生过世或辍学,我希望有一个删除选项,以从表中删除其所有记录。 So please help me to solve this by PHP code and displays it in HTML while using a search form. 因此,请帮助我通过PHP代码解决此问题,并在使用搜索表单的同时将其显示为HTML。

您可以尝试mysql_query()mysql_assoc_array()

Enforcing referential integrity at the database level is the way to go. 在数据库级别加强引用完整性是必须的。 I believe when you said you wanted the delete "to delete his all records from my tables" you meant deleting the row and all its child records. 我相信,当您说要删除“从我的表中删除他的所有记录”时,您的意思是删除该行及其所有子记录。 You can do that by using foreign keys and ON DELETE CASCADE . 您可以通过使用外键和ON DELETE CASCADE

CREATE TABLE students 
(   
    student_id INT NOT NULL,
    name VARCHAR(30) NOT NULL,
    PRIMARY KEY (student_id)
) ENGINE=INNODB;


CREATE TABLE fee_details
(
    id INT, 
    date TIMESTAMP,
    student_id INT,

    FOREIGN KEY (student_id) REFERENCES students(student_id)
        ON DELETE CASCADE
) ENGINE=INNODB;

With this, when a student is deleted from the students table, all its associated records will be deleted from fee_details . 这样,当从students表中删除students ,所有与之相关的记录都将从fee_details删除。

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

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