mysql之4;

1表之间的关系:

2select查询语句:

1表之间的关系

(1)多对一:(一个表里的多条记录对应另一个表里的一个记录)

建立多对一的关系需要注意
1 先建立被关联的表,被关联的字段必须保证是唯一的
2 再创建关联的表,关联的字段,一定要保证是可以重复的
ps:关联的字段一定是来自于被关联的表对应字段的值
代码:
create table dep(#部门表
id int primary key auto_increment, #被关联的字段必须保证是唯一的#id字段是主键并且是自增的
name varchar(20),#
comment varchar(50)
);
create table emp(#员工表
id int primary key auto_increment,
name varchar(20),
dep_id int, #关联的字段,一定要保证是可以重复的
constraint fk_depid_id foreign key(dep_id)  references dep(id)#定义外键
on update cascade#这个是表示这两个是跟随被关联的表一起更改或者删除的
on delete cascade
);

(2)一对一

create table user(#建立user表
uid int primary key auto_increment,#主键且自增
name varchar(15)#用户的名字
);
insert into user(name) values#插入数据
('frank1'),
('frank2'),
('frank3'),
create table admin(#建立admin表
id int primary key auto_increment,#主键且自增
user_id int unique,#确保是独一无二的
password varchar(20),#密码的多少
foreign key(user_id) references user(uid)#关联到user的uid确保foreign 是独一无二的
on update cascade#后面这个可以确保关联的表可以跟着被关联的一起改动或者删除
on delete cascade
);
insert into admin(user_id,password) values
(1,'frank3714'),
(2,'alfrank371asdf4')

(3)多对多关系

多对多代码: 
create table author (#创建作者信息 id int primary key auto_increment, name char (10)); create table books (#创建书籍信息 id int primary key auto_increment, name char (10)); create table books_authors(#建立一个关系表 id int primary key auto_increment ,#主键且自增 book_id int not null,#不为空 author_id int not null ,#不为空 unique(book_id,author_id),#联合唯一 foreign key (book_id) references books(id)#设置外键 on delete cascade#这两个是说明关联表是跟随被关联表一起变动 on update cascade , foreign key (author_id ) references author(id)#设置外键 on delete cascade on update cascade );

2select查询语句:

mysql:增、删、改、查;  查是我们用到数据库最多的就是查询数据

我们以前学过基本的查询语句:select * from  t1;

我们来看下一个where语句和(and,between and ,not ,or ,in、is 、like等)

select * from t1 where  id=5;

select name,age where    salary>1000 and salary <2000;可以写成select name,age where salary between 1000 and 2000;

select name,age where  salary not between 1000and 2000;

select name,salary from employee where salary = 10000 or salary = 20000 or salary = 30000;
select name,salary from employee where salary in (10000,20000,30000);
select salary from employee where name like '%ank%'; #like 是模糊匹配 %可以代表任意字符(可以代表多个)
select salary from employee where name like 'frank_';  #like 是模糊匹配 _可以代表任意一个字符
select * from employee where dep_comment is Null;#is Null 判断是否为空;有值用=
select * from employee where dep_comment = Null;#这个是错误的
select * from employee where dep_comment is not Null;
group by 是分组(以什么为分组)
select depart_id,count(id)  from employee group by depart_id;


原文地址:https://www.cnblogs.com/1a2a/p/7490350.html