Mysql(3)

20240529

约束条件:限制表中的数据,保证数据的准确,可靠的规则

  1. not null /null

  2. unsigned

  3. zerofill

  4. unique:唯一数据

  5. primary key: 主键,便于查询 =not null +unique

    1. 主键约束:添加的约束规则
    2. 主键字段:添加了主键约束的字段
    3. 主键值:主键字段的值
    4. 主键的作用:自动添加索引-index,主键值是当前数据的唯一标识
    5. 单一主键:列级约束
      1. create table ''(id int primary key)
      2. create tatle ''(id int,constraint user_id_k primary key(id))#重命名主键为user_id_k
    6. 复合主键:表级约束
      1. create table ''(id int primary key)
      2. create table ''(id int,name varchar(32),constraint user_id_k primary key(id,name))#重命名主键为user_id_k
    7. foreign key:外键,便于表之间创建关联关系
      1. 外键约束:字段外键的约束规则
      2. 外键字段:添加外键约束规则的字段
      3. 外键值
      4. 外键关系:
        1. 一对一:外键关系建议建立在使用频率高的表上
        2. 一对多(单向):外键关系创建在"多"中
          1. 先创建一
          2. 创建多:指定外键
          3. 给1插入数据
          4. 给多插入数据
        3. 多对多(双向)
          1. 创建1.2表
          2. 创建第三方表,通过第三表来存储关联关系
      5. 外键创建语法
        1. create table ''()#创建表1
        2. create table ""(,foreignkey(..) references ''...)#创建表2 ,指定外键关系
      6. 级联更新、删除
        1. foreignkey(..) references ''... on update cascade
        2. foreignkey(..) references ''... on delete cascade
    8. 自然主键和业务主键
    --查看当前表的字段限制
    show databases;
    use information_schema;
    show tables;
    desc table_constrains;
    select constrains_name from table_constrains where table_name ='当前表名'
    

    过滤条件

    1. where:对整体数据的筛选条件
      1. 添加:=/is
      2. 与条件:and/between...and...
      3. 或条件:or/ in ()
      4. 模糊:.. like'%..%'
      5. 长度条件:char_length(..)=../ .. like '__________'
      6. 取反: not
    2. group by:透视(分组查看)
      1. select ..,.. from '' group by ..#group by后面的字段必须在select里
      2. select max(..)
      3. select .. as ..
      4. select min(..)
      5. select avg(..)
      6. select sum(..)
      7. select count(..)
      8. group_concat(..,..):聚合函数的具体值,可以拼接
      9. concat:没有分组数据的拼接
    3. having:分组之后的筛选,功能同where
    4. distinct:去重
      1. select distinct ..,.. from ''
    5. order by:排序
      1. select * from '' order by .. ,.. asc/desc;
  6. limit:限制数据量

  7. 限制数据总量:limit n #n为数据量

  8. 分页效果: limit 1,5 (逗号前是索引开始位置,后是数据量)

  9. 正则表达式: 字段 REGEXP '表达式'

    1. ^a:以a开头

      1. select * from* where * REGEXP '表达式'
    2. a$:以a结尾

    3. . 一个字符

      • *零次或无数次

        ?一次或零次

        • +一次或无数次

多表查询和子查询

多表查询:联表查询

  1. 把多张表合并为一张表,在合并后的表中查询数据
  2. select * from 表1 join on 表2 表1.字段=表2.字段
  3. 笛卡尔积:select * from 表1,表2 #获得n*m条数据
  4. select * from t1,t2 where t1.* =t2.*
  5. join on
    1. inner join on:内连接,两张表都有的数据才会被保留
    2. left join on:左连接,左表有的数据才会保留
    3. right join on;右连接,右表有的数据才会保留
    4. union on:两张表都拼上(left union right)

子查询

  1. 先查一条数据,再将这条数据的结果作为下一条查询语句的起始
posted @   zenopan  阅读(8)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示