1. 程式人生 > >MySQL建立、修改表、表的約束

MySQL建立、修改表、表的約束

一、MySQL建立、修改表,有2種方式:

1、在圖形介面工具中點選選單提示進行操作,如:


2、使用SQL語句操作,如下:

-- 切換資料庫
use sh;
-- 如果存在就刪除表
drop table if exists room;
-- 如果表不存在就建立表,room是表名,rid列名
create table if not exists room(
    rid int primary key,-- primary key設定列為主鍵
    rname varchar(50) not null,-- not null該列資料不能為空
    beds int,
    address varchar(255));
-- 查看錶所有列的資訊
describe room;
-- 修改表,新增主鍵約束
alter table student 
add constraint c_id primary key(sid);-- constraint約束,c_id表示約束的名字,sid表示在student表中新增為主鍵的列

3、修改表的用法:

1)新增列:

<span style="font-size:12px;">-- 新增列,預設最後一列
alter table student add column adfiy varchar(50);
-- 新增列,指定位置:第一列
alter table student add column sex int first;
-- 新增列,指定位置:name列的後面
alter table student add column major int after name;</span>
2)修改列:

      a)修改列的名稱:

-- 修改列的名稱,相當於把之前的列刪除,再新增列
alter table student change column adfiy adfies varchar(10);

      b)修改列的型別:

<span style="font-size:12px;">alter table student modify column adfiy varchar(10);</span>

3)刪除列:

<span style="font-size:12px;">alter table student drop column adfies;</span>
4)重命名錶:
<span style="font-size:12px;">alter table student rename to students;</span>

二、MySQL中表的約束(使用關鍵字constraint):

1、主鍵約束:主鍵列不能為null 且唯一,建立表和修改表時指定主鍵的方式,如上面的程式碼。

2、唯一約束:非主鍵列唯一。

1)建立表時指定唯一約束:

create table if not exists room(
    rid int primary key,
    rname varchar(50) not null,
    beds int,
    address varchar(255),
    bossId int,
    -- constraint約束關鍵字 unique_name定義的約束名稱  unique是唯一約束關鍵字,rname表示約束的列
    constraint unique_name unique (rname));

2)修改表時,新增唯一約束:

alter table room 
add constraint unique_name unique(beds);
3、外來鍵約束:約束引用其他表主鍵的列,該列的值只能是主鍵列的值。建立表時指定外來鍵約束:
drop table if exists room;
create table if not exists room(
    rid int primary key,
    rname varchar(50) not null,
    beds int,
    address varchar(255),
    bossId int,
    -- constraint約束關鍵字 fk_name定義的約束名稱  foreign key是外來鍵約束關鍵字
    constraint fk_name foreign key (bossId)
    references student(sid)  -- references指定約束
);