2、SQL数据类型、限制条件

关系型数据库系统

数据类型

  1. 整数:int , 4个字节

    范围 数量:2^32 - 1

  • 有符号:-2147483648~2147483647
  • 无符号:0~4294967295
  1. 小数:decimal,decimal(5, 2)表示共存5位数,小数占2位,整数占3位

  2. 字符串:varchar

    范围 0~65533

  3. 日期时间类型:datetime

    范围(1000-01-01 00:00:00 ~ 9999-12-31 23:59:59)

约束

  • 主键primary key:物理上的额存储顺序
  • 非空not null:此字段不允许为空
  • 唯一unique:此字段的值不允许重复
  • 默认值default:当不输入值时,默认为default
  • 外键foreign key:维护两个表之间的关联关系

条件

比较运算:>、<、=、!=

逻辑运算:and、or、not

模糊查询:like、%任意多个字符、_单个字符

范围查询:in在一个非连续的范围内、between … and … 表示在一个连续的范围内

空判断:null与’'是不同的,is null

排序

语法:order by 列1 asc|desc, 列2 asc|desc, … , 列n asc|desc

select * from tb_name order by id asc, name desc, age asc, height asc;

聚合函数

select count(*) from student;

select max(age) from student where id=1;

select min(age) from student where id=2;

select sum(age) from student where age=18;

select avg(age) from student;

分组

语法:
select 列1, 列2, 聚合函数 from tb_name group by 列1, 列2...

例子:
select age, count(*) from tb_name group by age;
select name, count(*) from tb_name group by name;

分组后数据筛选
select  列1, 列2, 聚合函数 from tb_name 
group by 列1, 列2...
having 列1, 列2...

select sex, count(*) from student group by sex having sex="男";

分行

limit start, count

select * from tb_name limit 0,3

分页

select * from tb_name limit (n-1)*m, m

去重

# 单字段去重
select distinct age from tb_name;

# 多字段去重
select distinct age,id from tb_name;

返回目录

THE END
< <上一篇
下一篇>>