sqlÖÐreferenceÔõôÓÃ
sql ÖÐµÄ reference Òªº¦×ÖÓÃÓÚ½ç˵Íâ¼üÔ¼Êø£¬È·±£Êý¾ÝÍêÕûÐÔ¡£Íâ¼üÔ¼ÊøÒªÇó×Ó±íÖеÄÁÐÒýÓø¸±íÖеÄÖ÷¼üÁС£Ó﷨Ϊ£ºalter table child_table add foreign key (child_column) references parent_table (parent_column) [on delete action] [on update action]¡£ÀûÒæ°üÀ¨£ºÊý¾ÝÍêÕûÐÔ¡¢¼ò»¯Êý¾ÝÖÎÀí¡¢Ìá¸ßÐÔÄÜ¡£
SQL ÖÐµÄ REFERENCE Ó÷¨
ÔÚ SQL ÖУ¬REFERENCE Òªº¦×ÖÓÃÓÚ½ç˵Íâ¼üÔ¼Êø£¬ÒÔÈ·±£Êý¾ÝÍêÕûÐÔ¡£Íâ¼üÔ¼ÊøÊÇÒ»ÖÖ»úÖÆ£¬Ëü»®¶¨Ò»¸ö±íÖеÄÁбØÐèÒýÓÃÁíÒ»¸ö±íÖеÄÖ÷¼üÁÐÖеÄÖµ¡£
Óï·¨
ALTER TABLE child_table ADD FOREIGN KEY (child_column) REFERENCES parent_table (parent_column) [ON DELETE action] [ON UPDATE action];
µÇ¼ºó¸´ÖÆ
ÆäÖУº
child_table£ºÒýÓø¸±íµÄÍâ¼üËùÔÚµÄ×Ó±í¡£
child_column£º×Ó±íÖÐ×÷ΪÍâ¼üµÄÁС£
parent_table£º°üÀ¨±»ÒýÓõÄÖ÷¼üµÄ¸¸±í¡£
parent_column£º¸¸±íÖб»ÒýÓõÄÖ÷¼üÁС£
ON DELETE action£ºÖ¸¶¨µ±¸¸±íÖеļͼ±»É¾³ýʱ¶Ô×Ó±íÖÐÊÜÓ°Ïì¼Í¼µÄ´¦Àí·½·¨¡£¿ÉÄܵÄÑ¡ÏîÓÐ CASCADE¡¢RESTRICT¡¢SET NULL ºÍ SET DEFAULT¡£
ON UPDATE action£ºÖ¸¶¨µ±¸¸±íÖеļͼ±»¸üÐÂʱ¶Ô×Ó±íÖÐÊÜÓ°Ïì¼Í¼µÄ´¦Àí·½·¨¡£¿ÉÄܵÄÑ¡ÏîÓë ON DELETE Ïàͬ¡£
Ó÷¨Ê¾Àý
¼ÙÉèÎÒÃÇÓÐÒ»¸öÃûΪ students µÄ±í£¬ÆäÖаüÀ¨Ñ§ÉúÐÅÏ¢£¬ÁíÒ»¸öÃûΪ classes µÄ±í£¬ÆäÖаüÀ¨°à¼¶ÐÅÏ¢¡£ÎªÁËÈ·±£Ñ§Éú¼Í¼ֻÄÜÒýÓÃÓÐÓõİ༶±àºÅ£¬ÎÒÃÇ¿ÉÒÔʹÓÃÈçÏÂÓï¾ä½¨ÉèÍâ¼üÔ¼Êø£º
ALTER TABLE students ADD FOREIGN KEY (class_id) REFERENCES classes (class_id) ON DELETE CASCADE ON UPDATE RESTRICT;
µÇ¼ºó¸´ÖÆ
Óŵã
ʹÓà REFERENCE Òªº¦×Ö¾ÙÐÐÍâ¼üÔ¼ÊøµÄÀûÒæ°üÀ¨£º
È·±£Êý¾ÝÍêÕûÐÔ£¬±ÜÃâÒâÍâ²åÈëºÍ¸üС£
¼ò»¯Êý¾ÝÖÎÀí£¬ÎÞÐèÊÖ¶¯¼ì²éºÍ¸üÐÂÖµ¡£
Ìá¸ßÊý¾Ý¿âÐÔÄÜ£¬Í¨¹ýË÷ÒýÇ¿ÖÆÖ´ÐÐÔ¼Êø¡£
ÒÔÉϾÍÊÇsqlÖÐreferenceÔõôÓõÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡