MySQL5.7 建庫建表的命令


https://blog.csdn.net/qq_36381242/article/details/90409164

習題源自 《MySQL 5.7從入門到精通》清華大學出版社 --第四章數據表的基本操作

1 創建數據庫Market,在market中創建數據庫表customers, customers表結構如表1

(1)創建數據庫market

DELIMITER //
create database market;

 

(2)創建數據庫表customers

-- 指定操作在market數據中進行
use market;
 
-- 創建customers表
create table customers(
c_num int(11) primary key not null unique auto_increment,
c_name varchar(50),
c_contact varchar(50),
c_city varchar(50),
c_birth datetime not null
)ENGINE=innodb DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;

(3)將c_contact字段插入c_birth之后

alter table customers modify c_contact varchar(50) after c_birth;

(4)將c_name字段類型改為varchar(70)

alter table customers modify c_name varchar(70);

(5)將c_contact字段改名為c_phone

alter table customers change c_contact c_phone varchar(50);

(6)增加c_gender字段,數據類型為char(1)

alter table customers add c_gender char(1);

(7)將表名test修改為test1

-- 修改表名為c_city
rename table test to test1;

(8)刪除字段c_city

alter table customers_info drop c_city;

(9)修改數據表的存儲引擎為MyISAM

alter table customers_info engine = MyISAM;

(10)添加多個字段  name1 text類型、name2  json類型

  ALTER TABLE `table name` 
     ADD COLUMN `name1` text DEFAULT NULL,
     ADD COLUMN `name2` json(11) DEFAULT NULL;

 

2 在market數據庫中創建數據表orders,orders表結構如表2

(1)創建數據表orders,其中在c_id字段上添加外鍵約束,關聯customers表中的主鍵c_num

create table orders(
    o_num int(11) PRIMARY KEY not null unique auto_increment,
    o_date date,
    c_id int(varchar50) 
 
 );
 
-- 因為外鍵列的數據類型與父表關聯的列的數據類型要匹配,且表的存儲引擎要一樣,不然會報錯
-- 在MySQL5.5以上,表的存儲引擎默認為是InnoDB,因為在上一題中關聯的表改了存儲引擎,所以這里也要改
 alter table orders engine = MyISAM;
 alter table orders  add constraint fk_order_custom FOREIGN KEY(c_id) references customers_info (c_num);

(2)刪除 orders 表的外鍵約束,然后刪除表customers

-- 因為此處刪除的表與其他表有索引關聯,因此在刪表之前要刪除外鍵約束

 alter table orders drop Foreign key fk_order_custom;

 drop table customers_info;

數據庫的基本操作 

 

 

 

 

數據表的基本操作

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM