zoukankan      html  css  js  c++  java
  • sql语句之约束条件

    not null约束,需设置默认值

    sex enum('male','female') not null default 'male'

    unique 约束,值唯一

    单列唯一:

    create table department(

      id int unique,

      name char(10) unique);

    或者

    create table department(

      id int,

      name char(10),

      unique(id),

      unique(name));

    联合唯一:

    create table department(

      id int,

      name char(10),

      unique(id,name));

    primary key

    满足 not null,unique

    对innodb存储引擎来说,一张表内必须有一个主键,当不指定主键时,会默认选一列满足not null和unique的列做主键,如果没有,会设一个隐藏列做主键。

    单列主键和复合主键。

    primary key(id1,id2)

    auto_increment

    create table t20(

      id int primary key auto_increment,    #如果不指定id值,id会自动自增,如果指定则按指定的id值

      name char(16))

      AUTO_INCREMENT = 4;     # 设定id起始值为4

    alter table set auto_increment = 1   # 修改起始值

    补充:

      show variables like 'auto_inc%'  # 查询变量

      auto_increment_increment     # 步长,默认为1

      auto_increment_offset       # 起始偏移量,默认为1

      set session auto_increment_increment=5;  # 该步长基于会话级别,会话关闭,步长失效。而sql server可以给表设置步长  

      set global auto_increment_increment=5; # 设置所有会话,会话关闭后再开启,步长还是5

      清空表要用truncate,如truncate t20,能置自增的序列为初始状态,而delete不能,delete宜和where配合删除具体一行。

    foreign key

    先建被关联的表,并保证被关联的字段唯一。

    再建关联表:

    dept_id int,

    foreign key(dept_id)  references dept(id) on delete cascade on update cascade   

    或 CONSTRAINT fk_dept foreign key(dept_id) REFERENCE dept(id)

     # cascade会导致删除和更新被关联的表时,同步删除关联表中相应外键下的记录,否则不能删除被关联表,除非先删除关联表或修改关联表中外键

    实际应用中,尽量少用foreign key

    可以有复合外键,前提是引用的是复合主键

  • 相关阅读:
    关于object和embed
    关于跨域问题的解决办法
    SQL 中 SELECT 语句的执行顺序
    sql子查询 嵌套SELECT语句
    PL/SQL中SELECT总结
    SQL Server
    SQL Server SELECT逻辑处理顺序
    SQL 基础:Select语句,各种join,union用法
    sql基础知识(新手必备)
    mysql处理海量数据时的一些优化查询速度方法
  • 原文地址:https://www.cnblogs.com/stin/p/8559173.html
Copyright © 2011-2022 走看看