055_ foreign key constraint database

# Create Table students from the class table where students table depends on the class list 
the CREATE TABLE tbl_class ( 
    the above mentioned id int (11 ) PRIMARY KEY AUTO_INCREMENT, 
    name char (20 ), 
    Number The int (11 ) 
); 

the CREATE TABLE tbl_student ( 
    the above mentioned id int (11 ) KEY the AUTO_INCREMENT a PRIMARY, 
    name char (50 ), 
    Age char (. 11 ), 
    class_id int (. 11 ), 
    cONSTRAINT haha a FOREIGN KEY (class_id) the REFERENCES tbl_class (ID) 
    the ON the ON the DELETE Cascade Cascade the UPDATE     
); constraint

*** : This is a name from the foreign key constraint, usually to remove the foreign key constraint according to the name. The main constraint is the foreign key constraint is dependent table, 
no effect on the dependent table. 
There are four foreign key constraint attribute value = 
    Cascade: cascading deletes and updates, when the dependency table is deleted, all data will be deleted in the dependent table.
    the SET null : When you delete the dependent table, the data since Beijing will set the table as null
    the restrict : dependent table does not delete finished, be dependent on the table can not be deleted. Is the default value.
    Action NO : re mysql and restrict the same.
    the SET default : innoDB NDB and can not be used to change parameters. 

# Foreign key constraint delete 
the ALTER TABLE tbl_student the DROP a FOREIGN KEY haha; 
Delete from tbl_class WHERE ID = 2 ; 

# add foreign key constraint  
ALTER TABLE tbl_student ADD CONSTRAINT haha FOREIGN KEY (class_id) REFERENCES tbl_class (id)
the ON the ON the DELETE Cascade Cascade the UPDATE 

# delete two tables 
drop Table tbl_student; 
drop Table tbl_class;

 
# view the index of a table, the primary key index can be seen, the foreign key index can also be seen, but restrict out view constraint attribute value. 
show index from tbl_student; 

create table # View, you can view the foreign key constraint property values, but only re-doc window. 
show create table tbl_student;

 

Guess you like

Origin www.cnblogs.com/pogusanqian/p/12526767.html