约束类型测试2

===设置主键约束 PRIMARY KEY

目的:

1、primary key 字段的值是不允许重复,且不允许NULL(UNIQUE + NOT NULL)

2、单列做主键

3、多列做主键(复合主键)

创建表

示例1:

表school.student6 方法一

mysql> create table student6(

id int primary key not null auto_increment,

name varchar(50) not null,

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

age int not null default 18

);

Query OK, 0 rows affected (0.00 sec)

示例2:

表school.student6 方法一

mysql> create table student6(

id int primary key not null auto_increment,

name varchar(50) not null,

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

age int not null default 18

);

Query OK, 0 rows affected (0.00 sec)

查询表结构

desc student6;

+-------+-----------------------+------+-----+---------+----------------+

| Field | Type                  | Null | Key | Default | Extra          |

+-------+-----------------------+------+-----+---------+----------------+

| id    | int(11)              | NO  | PRI | NULL    | auto_increment |

| name  | varchar(50)          | NO  |    | NULL    |                |

| sex  | enum('male','female') | NO  |    | male    |                |

| age  | int(11)              | NO  |    | 18      |                |

+-------+-----------------------+------+-----+---------+----------------+

4 rows in set (0.00 sec)

![如图](https://upload-images.jianshu.io/upload_images/15572377-beab11b095f1bd29.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

插入数据

mysql> insert into student6 values (1,'alice','female',22);

mysql> insert into student6(name,sex,age) values

('jack','male',19),

('tom','male',23);

Query OK, 2 rows affected (0.00 sec)

Records: 2  Duplicates: 0  Warnings: 0

查询表内容

mysql> select * from student6;

+----+-------+------+-----+

| id | name  | sex  | age |

+----+-------+------+-----+

|  1 | alice | female |  22 |

|  2 | jack  | male  |  19 |

|  3 | tom  | male  |  23 |

+----+-------+------+-----+

3 rows in set (0.00 sec)

(注意观察id列,并没有输入内容,自动增长。如果在此列插入空值呢?)

插入非法数据

MariaDB [company]> insert into student6(name,sex,age) values  (3,'jack','male',19);

ERROR 1136 (21S01): Column count doesn't match value count at row 1

![图示1](https://upload-images.jianshu.io/upload_images/15572377-c40b3cbe6bee6929.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

主键设置了自动增长,再次尝试插入数据。成功(注意不要插入主键)

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 一、数据库简介 1.数据库系统 1.1数据库 DataBase【DB】,指的是长期保存到计算机上的数据,按照一定顺...
    郑元吉阅读 3,757评论 0 6
  • 数据库:存放数据的仓库; 硬盘 运行内存 mysql 现在被oracle收购了 oracle oracle公司 s...
    凤之鸠阅读 4,688评论 0 0
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,206评论 0 10
  • MYSQL 基础知识 1 MySQL数据库概要 2 简单MySQL环境 3 数据的存储和获取 4 MySQL基本操...
    Kingtester阅读 12,406评论 5 115
  • There were fine sunsets even in the square, sometimes. On...
    Mr_Oldman阅读 1,684评论 0 0

友情链接更多精彩内容