1:主键约束 primary key
- 约束: 创建表时给表字段添加的限制条件
- 主键: 表示数据唯一性的字段称为主键
- 主键约束: 唯一且非空
- 举例:
create database day2db charset=utf8;
use db;
create table t1(id int primary key,name varchar(20));
insert into t1 values(1,'a');
insert into t1 values(2,'b');
insert into t1 values(2,'c'); 报错:Duplicate entry '2' for key 'PRIMARY'
insert into t1 values(null,'c'); 报错: Column 'id' cannot be null
主键约束+自增 auto_increment
- 自增规则: 从历史最大值+1
create table t2(id int primary key auto_increment,name varchar(20));
insert into t2 values(null,'a');
insert into t2 values(null,'b');
insert into t2 values(10,'c');
insert into t2 values(null,'d');
delete from t2 where id>=10;
insert into t2 values(null,'e');
比较运算符 > < >= <= = !=和<>
- 查询x小于等于x的员工姓名和工资
select name,sal from emp where sal<=x;
- 查询x的名字
select name from emp where job='x';
- 查询x号部门的员工姓名,工资和工作
select name,sal,job from emp where dept_id=x;
- 查询不是x的员工姓名和工作(两种写法)
select name,job from emp where job!="x";
select name,job from emp where job<>"x";
与或非 and or not
- and: 查询多个条件同时满足时使用
- or : 查询多个条件满足一个条件时使用
- not: 取反
- 查询x号部门工资高于y的员工信息
select * from emp where dept_id=x and sal>y;
- 查询x号部门或工资等于y的员工信息
select * from emp where dept_id=x or sal=y;
- 查询有上级领导的员工姓名
select name from emp where manager is not null;
- 查询出x和y的名字
select name from emp where job='x' or job='y';
- 查询有奖金的x名字和奖金
select name,comm from emp where comm>0 and job='x';
select name,comm from emp where comm is not null and job='x';
between x and y 两者之间 包含x和y
- 查询工资在x到y之间的员工信息
select * from emp where sal between x and y;
- 查询工资在x到y以外的员工信息
select * from emp where sal not between x and y;
in(x,y,z)
- 当查询某个字段的值为多个的时候使用
- 查询工资等于x,y和z的员工信息
select * from emp where sal in(x,y,z);
- 查x和y的员工信息
select * from emp where job in('x','y');
去重 distinct
- 查询x号部门中出现了哪几种不同的工作
select distinct job from emp where dept_id=x;
- 查询员工表中出现了哪几种不同的部门id
select distinct dept_id from emp;
模糊查询 like
- _: 代表1个未知字符
- %: 代表0或多个未知字符
- 举例:
- 以x开头 x%
- 以x结尾 %x
- 以x开头y结尾 x%y
- 包含x %x%
- 第二个字符是x _x%
- 第三个是x倒数第二个是y __x%y_
- 查询姓x的员工姓名
select name from emp where name like "x%";
- 查询名字中包含x的员工信息
select * from emp where name like "%x%";
- 查询名字以x结尾的员工姓名
select name from emp where name like "%x";
- 查询工作中包含x并且工资大于1500的员工信息
select * from emp where job like "%x%" and sal>1500;
- 查询工作中第二个字是x的员工姓名和工作
select name,job from emp where job like "_x%";
- 查询1号和2号部门中工作以x开头的员工信息
select * from emp where dept_id in(1,2) and job like "x%";