数据库笔记——SQL语言DQL语句-CSDN博客
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
schema等于database 数据库
datagrip中使用控制台进行操作
右键new QueryConsole
创建表格create table中
1. 括号内不管是定义属性还是声明约束都使用逗号分隔最后一句不用逗号
2. 括号外使用分号
DDL数据库定义语言用于创建/修改数据库/表结构相当于修改表头有哪些列
create table student(
id int auto_increment primary key,
name varchar(10),
number varchar(10)
);
insert into student values (null, '小明','20231014'),
(null,'小新','20231600');
create table course(
id int auto_increment primary key ,
name varchar(10)
);
insert into course values (null,'java'),
(null,'PHP'),
(null,'MySQL'),
(null,'Hadoop');
create table student_course(
id int auto_increment primary key ,
id_stu int ,
id_cou int,
foreign key (id_stu) references student(id),
foreign key (id_cou) references course(id)
);
insert into student_course values (null,1,1),
(null,1,2),
(null,1,3),
(null,2,2),
(null,2,3);
DML数据库操纵语言用于增删/修改表中数据相当于修改表中一行数据
约束
1. primary key主码约束
主码属性必须非空且唯一
primary key (dept_name)
2. foregin key references外键约束
foreign key (dept_name) references department(id),
3. not null非空
name varchar(20) not null
DQL语句(数据库查询语言)
单关系查询
select dept_name from instructor;
删除重复使用distinct关键词
select distinct dept_name from instructor;
使用all显式指明不去除重复
select all dept_name from instructor;
select name
from instructor
where dept_name='Comp.Sci.' and salary>70000;
多关系查询
select name, instructor, dept_name, building
from instructor, department
where instructor.dept_name=department.dept_name;
如果一个属性出现在两个关系中我们使用关系名作为前缀如果属性只出现在一个关系中则不需要前缀
执行顺序from -> where -> select
使用自然连接
select name, instructor, dept_name, building
from instructor natural join department;
多表查询
多对多
建立第三张中间表
内连接
隐式内连接
select e.name,d.name from emp e,dept d where e.dept_id=d.id;
或
select e.name,d.name from emp,dept where emp.dept_id=dept.id;
显式内连接
select emp.name,dept.name from emp inner join dept on emp.dept_id=dept.id;
分组查询
当SOL查询使用分组时一个很重要的事情是需要保证出现在select语句中但没有被聚集的属性只能是出现在group by子句中的那些属性。换句话说任何没有出现在group by子句中的属性如果出现在select 子句中的话它只能出现在聚集函数内部否则这样的查询就是错误的。例如下述查询是错误的因为ID没有出现在group by 子句中但它出现在了select子句中而且没有被聚集:
执行顺序from -> where -> group by -> having -> select
例查询年龄小于45的员工并根据工作地址分组获取员工数量大于等于3的工作地址
select address, count(*) from emp where age<45 group by address
having count(*)>=3;
where在分组前执行分组时会执行聚合函数having在分组后执行
查询字段一般为聚合函数和分组字段
关键词
distinct
auto_increment自动增长
id int auto_increment primary key,