一、多对多连表操作(外键操作)
1.创建表一:
CREATE TABLE `man` (
`nid` int(11) NOT NULL AUTO_INCREMENT, `name` char(10) DEFAULT NULL, PRIMARY KEY (`nid`)) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;2.创建表二:
CREATE TABLE `women` (
`nid` int(11) NOT NULL AUTO_INCREMENT, `name` char(10) DEFAULT NULL, PRIMARY KEY (`nid`)) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;3.创建表三:
CREATE TABLE `man_to_women` (
`nid` int(11) NOT NULL AUTO_INCREMENT, `man_id` int(11) NOT NULL, `women_id` int(11) NOT NULL, PRIMARY KEY (`nid`), KEY `to_man` (`man_id`), KEY `to_women` (`women_id`), CONSTRAINT `to_man` FOREIGN KEY (`man_id`) REFERENCES `man` (`nid`), CONSTRAINT `to_women` FOREIGN KEY (`women_id`) REFERENCES `women` (`nid`)) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;man_to_women有2个外键,1,man_to_women.man_id = man.nid 2,man_to_women.women.women_id = women.nid
查找man表中name数据在women表中对应的name数据
SELECT women.name as wname ,man.name as mname from man_to_women
LEFT JOIN man on man_to_women.man_id = man.nidLEFT JOIN women on man_to_women.women_id = women.nidwhere man.name = 'man1';显示数据:
wname mname
wo1 man1
wo2 man2
二、SQL视图
1.添加视图
create view view_name as
select * from XXX_table;
修改视图
alter view test as
SELECT * from man;删除视图
drop view test;
查询视图
SELECT * from man_to_women_view;
(注意:视图是一张伪表,不是一张真实的表)
三、存储过程procedure
1、创建procedure
delimiter $$
CREATE PROCEDURE proc_test(in p1 int ,inout p2 int ,out p3 int)begin
DECLARE x1 int ; DECLARE x2 int ; declare p3 int; set x1 = p1; set x2 = p2; set p3 = x1 + x2 ;end $$
delimiter ;
delimiter设置mysql的语句标识结束符,运行完成后改成;
procedure 有3类参数,1. in参数是传入的数值,2.inout参数既可以传入参数也可以传出参数 3.out参数为procedure的返回值(传入时需要定义传入的类型)
declare为定义一个变量,set为一个变量设定值,
运行procedure:
set @p=1;
call proc_test(5,@p,@u);SELECT @p,@u;三、触发器
创建触发器
create trigger name 操作前后 操作 on table _x for each row
begin
end
操作前后:before after 指操作之前执行 begin end代码段
操作:insert delete update三种操作会触发触发器
有两个属性,new和old
插入时,插入之前的值为old,插入之后的值为new
删除时,删除之前的值为old,插入之后的值为new
更新时,更新之前的值为old,插入之后的值为new
例如 new.属性A 指的是触发操作是属性A的值
11111