Mysql 数据类型 以及约束

时间:2022-03-21 07:12:06

数据类型

  • 整型 默认有符号

    无符号(unsigned) 和有符号 用 0 填充 zerofill

  • 约束的作用: 保证数据的完整性 和一致性

  • tinyint[ -128 , 127 ] 小整数 无符号(0,255)

  • int 整数

  • bigint 极大整数

  • 浮点型

    float 单精度

    double 双精度

    decimal 小数 精准的小数

  • 日期类型

    year 年份 date 年月日 time 时分秒 datetime 年月日时分秒

    now() 获取当前的事件( 根据数据类型 )

  • 枚举 和 集合

    enum('male 男', 'female 女', 'other') default 'male';

    enum("vip1","vip2","vip3","vip4") 指定范围内多选一

    set('play', 'music', 'read', 'study') 在指定范围内多选多

  • bool 类型

    使用 tingint(1) 来表示 boolean 类型

完整性约束

  • not null 如果单独设置 不能插入空值
  • default 默认如果设置了 not null 又设置了 default 插入空则走 default

unique key 唯一

  • 单列唯一

    unque (name)

  • 多列唯一

    unque (id), unque (name) 只要有一列相同 就不能插入

  • 联合唯一

    unque (id, name) 多列相同不能插入

primary key 主键

  • 单列主键

    id int primary key

  • 联合主键

    primary key(id, name)

  • 自增 auto_increment

    id int primary key auto_increment 设置主键自增

foreign key 外键

  • constraint 约束

    KEY `fk_course_teacher` (`teacher_id`),   -- 指定外键的key 
    CONSTRAINT `fk_course_teacher` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`tid`)
    --  指定外键关联  REFERENCES(参考)  teacher 表中的 tid 字段

创建表

-- ----------------------------
DROP TABLE IF EXISTS `city`;  -- 如果数据库中 有 city 表就先 删除 再 创建
CREATE TABLE `city` (
  `city_id` smallint(5) unsigned NOT NULL auto_increment,
  `city` varchar(50) NOT NULL,
  `country_id` smallint(5) unsigned NOT NULL,
  -- 时间   在创建新记录和修改现有记录的时候都对这个数据列刷新
  `last_update` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,  
  PRIMARY KEY  (`city_id`),  -- 指定主键 
  KEY `idx_fk_country_id` (`country_id`),  -- 指定外键 
  CONSTRAINT `fk_city_country` FOREIGN KEY (`country_id`) REFERENCES `country` (`country_id`)  on delete restrict   ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;  -- 指定引擎  默认字符集
  • 查看表
  • desc 表名;

清空表

  • 如果有自增 新增的数据 以之前的值开始

    delete from 表名;

  • 删除快 从零开始

    truncate table 表名;