MYSQLÍâ¼ü(Foreign Key)µÄʹÓÃ
ÔÚMySQL 3.23.44°æ±¾ºó£¬InnoDBÒýÇæÀàÐ͵ıíÖ§³ÖÁËÍâ¼üÔ¼Êø¡£
Íâ¼üµÄʹÓÃÌõ¼þ£º
1.Á½¸ö±í±ØÐëÊÇInnoDB±í£¬MyISAM±íÔÝʱ²»Ö§³ÖÍâ¼ü£¨¾Ý˵ÒÔºóµÄ°æ±¾ÓпÉÄÜÖ§³Ö£¬µ«ÖÁÉÙÄ¿Ç°²»Ö§³Ö£©£»
2.Íâ¼üÁбØÐ뽨Á¢ÁËË÷Òý£¬MySQL 4.1.2ÒÔºóµÄ°æ±¾ÔÚ½¨Á¢Íâ¼üʱ»á×Ô¶¯´´½¨Ë÷Òý£¬µ«Èç¹ûÔÚ½ÏÔçµÄ°æ±¾ÔòÐèÒªÏÔʾ½¨Á¢£»
3.Íâ¼ü¹ØϵµÄÁ½¸ö±íµÄÁбØÐëÊÇÊý¾ÝÀàÐÍÏàËÆ£¬Ò²¾ÍÊÇ¿ÉÒÔÏ໥ת»»ÀàÐ͵ÄÁУ¬±ÈÈçintºÍtinyint¿ÉÒÔ£¬¶øintºÍcharÔò²»¿ÉÒÔ£»
Íâ¼üµÄºÃ´¦£º¿ÉÒÔʹµÃÁ½Õűí¹ØÁª£¬±£Ö¤Êý¾ÝµÄÒ»ÖÂÐÔºÍʵÏÖһЩ¼¶Áª²Ù×÷£»
Íâ¼üµÄ¶¨ÒåÓï·¨£º
[CONSTRAINT symbol] FOREIGN KEY [id] (index_col_name, ...)
REFERENCES tbl_name (index_col_name, ...)
[ON DELETE {RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT}]
[ON UPDATE {RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT}]
¸ÃÓï·¨¿ÉÒÔÔÚ CREATE TABLE ºÍ ALTER TABLE ʱʹÓã¬Èç¹û²»Ö¸¶¨CONSTRAINT symbol£¬MYSQL»á×Ô¶¯Éú³ÉÒ»¸öÃû×Ö¡£
ON DELETE¡¢ON UPDATE±íʾʼþ´¥·¢ÏÞÖÆ£¬¿ÉÉè²ÎÊý£º
RESTRICT£¨ÏÞÖÆÍâ±íÖеÄÍâ¼ü¸Ä¶¯£©
CASCADE£¨¸úËæÍâ¼ü¸Ä¶¯£©
SET NULL£¨Éè¿ÕÖµ£©
SET DEFAULT£¨ÉèĬÈÏÖµ£©
NO ACTION£¨ÎÞ¶¯×÷£¬Ä¬Èϵģ©
MYSQL Íâ¼ü¶¨Òå
½¨Á¢Íâ¼üµÄÇ°Ì᣺ ±¾±íµÄÁбØÐëÓëÍâ¼üÀàÐÍÏàͬ(Íâ¼ü±ØÐëÊÇÍâ±íÖ÷¼ü)¡£
Íâ¼ü×÷Ó㺠ʹÁ½ÕűíÐγɹØÁª£¬Íâ¼üÖ»ÄÜÒýÓÃÍâ±íÖеÄÁеÄÖµ£¡
Ö¸¶¨Ö÷¼ü¹Ø¼ü×Ö£º foreign key(ÁÐÃû)
ÒýÓÃÍâ¼ü¹Ø¼ü×Ö£º references <Íâ¼ü±íÃû>(Íâ¼üÁÐÃû)
ʼþ´¥·¢ÏÞÖÆ: on deleteºÍon update , ¿ÉÉè²ÎÊýcascade(¸úËæÍâ¼ü¸Ä¶¯), restrict(ÏÞÖÆÍâ±íÖеÄÍâ¼ü¸Ä¶¯),set Null(Éè¿ÕÖµ£©,set Default£¨ÉèĬÈÏÖµ£©,[ĬÈÏ]no action
ÀýÈ磺
outTable±í Ö÷¼ü id ÀàÐÍ int
´´½¨º¬ÓÐÍâ¼üµÄ±í£º
create table temp(
id int,
name char(20),
foreign key(id) references outTable(id) on delete cascade on update cascade);
˵Ã÷£º°ÑidÁÐ ÉèΪÍâ¼ü ²ÎÕÕÍâ±íoutTableµÄidÁÐ µ±Íâ¼üµÄֵɾ³ý ±¾±íÖжÔÓ¦µÄÁÐɸ³ý µ±Íâ¼üµÄÖµ¸Ä±ä ±¾±íÖжÔÓ¦µÄÁÐÖµ¸Ä±ä¡£
Ïà¹ØÎĵµ£º
<! -- beans ÔªËØÊÇSpringÅäÖÃÎļþµÄ¸ùÔªËØ£¬ËùÓеÄSpring µÄÅäÖÃÎļþ¶¼Ó¦°´ÈçϽṹÊéдһ¡µ
<beans>
<!Ò»ÅäÖÃid ΪdataSource µÄbean£¬¸Ãbean ÊǸöÊý¾ÝԴʵÀýÒ»¡µ
<bean ¹¤d="dataSource" class="org.apache.corrunons.dbcp.BasicDataSource"
destroy-method="close">
<! È·¶¨Êý¾ÝÔ´µÄÇ ......
¡¾ÊéÃû¡¿¸ßÐÔÄÜMySQL£¨µÚ¶þ°æ£©
¡¾ÔÊéÃû¡¿High Performance MySQL, second edition
¡¾×÷Õß¡¿Baron Schwartz£¬Peter Zaitsev£¬Vadim
Tkachenko£¬Jeremy D.Zawodny£¬Arjen Lentz£¬Derek
J.Balling Öø
¡¾ÒëÕß¡¿ÍõС¶« Àî¾ü ¿µ½¨Ñ« Òë
¡¾³ö°æÉç¡¿µç×Ó¹¤Òµ³ö°æÉç
¡¾ÊéºÅ¡¿978- ......
1.select max(id) from user;
2.select last_insert_id() as id from user limit 1;
(Õâ¸ö²âÊԵķµ»ØidÒ»Ö±ÊÇ0£¬ÓеãÎÊÌâ)
3.´¢´æ¹ý³Ì
1£©
oracelÖÐ
create sequence seqID
minvalue 1
maxvalue 999999999999999999999999999
start with 1
increment by 1
nocache
order;
create or replace procedure ......
ʹÓÃmysqlÖеÄwith rollup¿ÉÒԵõ½Ã¿¸ö·Ö×éµÄ»ã×ܼ¶±ðµÄÊý¾Ý£º
±íÈçÏ£º
CREATE TABLE `test3` (
`id` int(5) unsigned NOT NULL AUTO_INCREMENT,
`name1` varchar(10) DEFAULT NULL,
`name2` varchar(10) DEFAULT NULL,
`cnt` int(2) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGI ......