MySQL表的約束

在這裏插入圖片描述

綜合案例

有一個商店的數據,記錄客戶及購物情況,有以下三個表組成

  • 商品goods(商品編號goods_id,商品名goods_name, 單價unitprice, 商品類別category, 供應商provider)
  • 客戶customer(客戶號customer_id,姓名name,住址address,郵箱email,性別sex,身份證card_id)
  • 購買purchase(購買訂單號order_id,客戶號customer_ id,商品號goods_ id,購買數量nums)

要求:

  • 每個表的主外鍵
  • 客戶的姓名不能爲空值
  • 郵箱不能重複
  • 客戶的性別(男,女)

-- 創建數據庫
create database if not exists story default character set utf8;
-- 選擇數據庫
use story;
-- 創建數據庫表
-- 商品
create table if not exists goods(
  goods_id int primary key auto_increment comment '商品編號',
  goods_name varchar(32) not null comment '商品名稱',
  unitprice int not null default 0 comment '單價,單位分',
  category varchar(12) comment '商品分類',
  provider varchar(64) not null comment '供應商名稱');

-- 客戶
create table if not exists customer(
  customer_id int primary key auto_increment comment '客戶編號',
  name varchar(32) not null comment '客戶姓名',
  address varchar(256) comment '客戶地址',
  email varchar(64) unique key comment '電子郵箱',
  sex enum('男','女') not null comment '性別',
  card_id char(18) unique key comment'身份證號');

-- 購買
create table if not exists purchase(
  order_id int primary key auto_increment comment'訂單號',
  customer_id int comment '客戶編號',
  goods_id int comment '商品編號',
  nums int default 0 comment  '購買數量',
  foreign key(customer_id) references customer(customer_id),
  foreign key(goods_id) references goods(goods_id));
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章