mysqlÖÐÍâÂëÊÇʲô
ÍâÂëÊÇ mysql ÖеÄÊý¾ÝÍêÕûÐÔÔ¼Êø£¬Í¨¹ýÒýÓÃÖ÷±íÖ÷¼üÁÐÈ·±£×Ó±íÊý¾ÝÓëÖ÷±íÒ»Ö¡£ÍâÂëÊÂÇéÔÀíÈçÏ£ºÈ·±£×Ó±íÒýÓõÄÖ÷±íÊý¾Ý±£´æ¡£¼¶ÁªÉ¾³ý£ºÖ÷±í¼Í¼ɾ³ýʱ£¬¼¶ÁªÉ¾³ý×Ó±íÏà¹Ø¼Í¼¡£¼¶Áª¸üУºÖ÷±íÖ÷¼ü¸üÐÂʱ£¬¼¶Áª¸üÐÂ×Ó±íÏà¹Ø¼Í¼¡£
ʲôÊÇ MySQL ÖеÄÍâÂ룿
ÍâÂ루Foreign Key£©ÊÇ MySQL ÖеÄÒ»ÖÖÊý¾ÝÍêÕûÐÔÔ¼Êø£¬ÓÃÓÚÈ·±£²î±ð±íÖ®¼äµÄÐоßÓÐÓÐÓÃÇÒÒ»ÖµĹØϵ¡£Ëüͨ¹ýÒýÓÃÁíÒ»¸ö±í£¨Ö÷±í£©ÖеÄÖ÷¼üÁÐÀ´ÊµÏÖ¡£
ÍâÂëÔõÑùÊÂÇ飿
µ±ÔÚ×Ó±íÖн¨ÉèÍâÂëʱ£¬Ëü»áÒýÓÃÖ÷±íÖеÄÖ÷¼üÁС£µ±Ïò×Ó±íÖвåÈëÒ»Ìõ¼Í¼ʱ£¬ÍâÂëÁеÄÖµ±ØÐèÆ¥ÅäÖ÷±íÖÐÏÖÓеÄÖ÷¼üÖµ¡£
ÍêÕûÐÔ£ºÍâÂëÔ¼Êø¿ÉÈ·±£×Ó±íÖÐÒýÓõÄÊý¾ÝʼÖÕÔÚÖ÷±íÖб£´æ¡£
¼¶ÁªÉ¾³ý£ºµ±Ö÷±íÖеļͼ±»É¾³ýʱ£¬¿ÉÒÔ¼¶ÁªÉ¾³ý×Ó±íÖÐËùÓÐÏà¹Ø¼Í¼£¬´Ó¶ø¼á³Ö±íÖ®¼äµÄ¹ØϵÍêÕûÐÔ¡£
¼¶Áª¸üУºµ±Ö÷±íÖеÄÖ÷¼üÖµ¸üÐÂʱ£¬¿ÉÒÔ¼¶Áª¸üÐÂ×Ó±íÖÐËùÓÐÏà¹Ø¼Í¼£¬´Ó¶ø¼á³ÖÒ»ÖÂÐÔ¡£
½¨ÉèÍâÂë
ʹÓÃÒÔÏÂÓï·¨½¨ÉèÍâÂ룺
ALTER TABLE ×Ó±í ADD FOREIGN KEY (ÍâÂëÁÐ) REFERENCES Ö÷±í(Ö÷¼üÁÐ);
µÇ¼ºó¸´ÖÆ
ʾÀý
¼ÙÉèÎÒÃÇÓÐÁ½¸ö±í£º¶©µ¥ºÍ¶©µ¥Ã÷ϸ¡£¶©µ¥Ã÷ϸ±íÓÐÒ»¸öÍâÂë order_id£¬ËüÒýÓà ¶©µ¥±íÖеÄÖ÷¼ü id¡£
CREATE TABLE ¶©µ¥ ( id INT PRIMARY KEY, ¿Í»§Ãû³Æ VARCHAR(255) ); CREATE TABLE ¶©µ¥Ã÷ϸ ( id INT PRIMARY KEY, order_id INT, ²úÆ·Ãû³Æ VARCHAR(255), ÊýÄ¿ INT, FOREIGN KEY (order_id) REFERENCES ¶©µ¥(id) );
µÇ¼ºó¸´ÖÆ
µ±Ïò ¶©µ¥Ã÷ϸ±í²åÈë¼Í¼ʱ£¬order_id ±ØÐè¶ÔÓ¦ÓÚ ¶©µ¥±íÖеÄÏÖÓÐ id Öµ¡£ÕâÈ·±£Á˶©µ¥Ã÷ϸʼÖÕÓëÓÐÓõĶ©µ¥¹ØÁª¡£
ÒÔÉϾÍÊÇmysqlÖÐÍâÂëÊÇʲôµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡