mysql表查询

74 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第3天,点击查看活动详情

一、约束条件

对表中的数据进行限定 , 保证数据的正确性 , 有效性 ,完整性。

约束条件在创建表的时候 , 写在数据类型后面

1、not null:非空约束,表示该字段不能为空 ,插入数据时必须传入数值

create table t2(
	id int(2),
    -- 该字段不允许不传值
	name char(5) not null
);

desc t2;
insert into t2 values(1024 , '阿宸');

2、default :设置默认值 , 在这个字段中如果没有数据的传入 , 会将默认值进行填充

create table t3(
	name char(3),
	-- 选项的默认值必须是选项里面有的
	sex enum('男','女')  default '男'
);

insert into t3 values('张三' , '女');
insert into t3(name) values('李四');

3、unique :唯一约束,字段值唯一不能重复

create table t4(
	id int unique,
	name char(4)
);

insert into t4 values
(1001 , '武则天'),
(1002 , '孙悟空'),
(1003 , '鲁班'),
(1004 , '孙尚香'),
(1005 , '雅典');

insert into t4 values(1006 , '王昭君');

4、primary key : 主键约束 , 确保数据唯一且不能为空

create table t5(
	id_card int primary key
);

insert into t5 values('440572');
insert into t5 values('440573');

5、auto_increment :自动增加(要把对应的字段设置为主键) , 会默认设置一个int类型 , 默认是从1或者从上一条数据的数值开始往后递增1.

create table t6(
	id int primary key auto_increment,
	name char(5)
);

insert into t6(name) values('小燕');
insert into t6 values(5 , '曦宇');
insert into t6(name) values('南枝');

二、数据更新

1、 表数据修改

update 表名 set 字段名= 值,…… where 条件;
-- 如果修改没有where子句的话 , 就整个字段中的所有数据全部修改

2、表数据删除

delete from 表名 where 条件;
# 如果没有where子句就会将整个表数据进行清空

三、数据查询进阶

1、模糊查询

like子句:在where子句中, 可以使用该子句以及关键字结合实现模糊查询

select * from 表名 where 字段名 like '关键字';

通配符

% : 表示匹配0个或者多个字符(NULL除外)
_ : 表示匹配任意一个字符(多个_ , 就匹配对应个数)
可以在通配符前后指定文字
select * from t7 where name like '刘%';
select * from t7 where name like '_宸';
select * from t7 where name like '%皓%';

2、消除重复项

对查询的结果去重 —— distinct

select distinct * from 表名;
select distinct height,name from t7;
select distinct sex from t7;
select distinct age from t7;
select distinct * from t7;

3、排序

在查询中添加拍寻 ,

select * from 表名 order by 字段名 desc;

默认为升序

asc :按照指定的字段升序排序(默认)

desc:降序排序

select * from t7 order by age;
select * from t7 order by age desc;


select * from t7 where age>20 order by height;
select * from t7 order by height desc;