创建并使用数据库mydb6_product 。
sql
mysql> create database mydb6_product;
Query OK, 1 row affected (0.01 sec)
mysql> use mydb6_product;
Database changed
新建employees表。 对于gender,有默认值意味着不为空,在建表时可以选择不写not null;
sql
mysql> create table employees(
-> id int primary key,
-> name varchar(50) not null,
-> age int,
-> gender varchar(10) default 'unknown',
-> salary float);
Query OK, 0 rows affected (0.03 sec)
mysql> desc employees;
+--------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+-------------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| name | varchar(50) | NO | | NULL | |
| age | int | YES | | NULL | |
| gender | varchar(10) | YES | | unknown | |
| salary | float | YES | | NULL | |
+--------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
新建orders表。
sql
mysql> create table orders(
-> id int primary key,
-> name varchar(100) not null,
-> price float,
-> quantity int,
-> category varchar(50));
Query OK, 0 rows affected (0.02 sec)
mysql> desc orders;
+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| name | varchar(100) | NO | | NULL | |
| price | float | YES | | NULL | |
| quantity | int | YES | | NULL | |
| category | varchar(50) | YES | | NULL | |
+----------+--------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
新建invoices表。
auto_increment:当对应的字段,不给值,会自动的被系统触发,系统会从当前字段中已经有的最大值+1操作,得到一个新的不同的值。
外键约束主要定义在从表上,主表则必须是有主键约束或唯一键约束.当定义外键后**,**要求外键列数据必须在主表的主键列存在或为null。格式为foreign key (从表的字段名称) references 主表名字(主表的字段名称)
sql
mysql> create table invoices(
-> number int primary key auto_increment,
-> order_id int,
-> in_date date,
-> total_amount float check(total_amount>0),
-> foreign key(order_id) references orders(id));
Query OK, 0 rows affected (0.03 sec)
mysql> desc invoices;
+--------------+-------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-------+------+-----+---------+----------------+
| number | int | NO | PRI | NULL | auto_increment |
| order_id | int | YES | MUL | NULL | |
| in_date | date | YES | | NULL | |
| total_amount | float | YES | | NULL | |
+--------------+-------+------+-----+---------+----------------+
4 rows in set (0.01 sec)