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
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,