数据库之主键约束

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');

比较运算符 > < >= <= = !=和<>

  1. 查询x小于等于x的员工姓名和工资

select name,sal from emp where sal<=x;

  1. 查询x的名字

select name from emp where job='x';

  1. 查询x号部门的员工姓名,工资和工作

select name,sal,job from emp where dept_id=x;

  1. 查询不是x的员工姓名和工作(两种写法)

select name,job from emp where job!="x";

select name,job from emp where job<>"x";

与或非 and or not

  • and: 查询多个条件同时满足时使用
  • or : 查询多个条件满足一个条件时使用
  • not: 取反
  1. 查询x号部门工资高于y的员工信息

select * from emp where dept_id=x and sal>y;

  1. 查询x号部门或工资等于y的员工信息

select * from emp where dept_id=x or sal=y;

  1. 查询有上级领导的员工姓名

select name from emp where manager is not null;

  1. 查询出x和y的名字

select name from emp where job='x' or job='y';

  1. 查询有奖金的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

  1. 查询工资在x到y之间的员工信息

select * from emp where sal between x and y;

  1. 查询工资在x到y以外的员工信息

select * from emp where sal not between x and y;

in(x,y,z)

  • 当查询某个字段的值为多个的时候使用
  1. 查询工资等于x,y和z的员工信息

select * from emp where sal in(x,y,z);

  1. 查x和y的员工信息

select * from emp where job in('x','y');

去重 distinct

  1. 查询x号部门中出现了哪几种不同的工作

select distinct job from emp where dept_id=x;

  1. 查询员工表中出现了哪几种不同的部门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_
  1. 查询姓x的员工姓名

select name from emp where name like "x%";

  1. 查询名字中包含x的员工信息

select * from emp where name like "%x%";

  1. 查询名字以x结尾的员工姓名

select name from emp where name like "%x";

  1. 查询工作中包含x并且工资大于1500的员工信息

select * from emp where job like "%x%" and sal>1500;

  1. 查询工作中第二个字是x的员工姓名和工作

select name,job from emp where job like "_x%";

  1. 查询1号和2号部门中工作以x开头的员工信息

select * from emp where dept_id in(1,2) and job like "x%";

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值