Chapter 2

1.Create a sample database:

1.cmd

2.mysql -u root -p

3.create database bank;

4.grant all privileges on bank.* to 'vcsql'@'localhost' identified by 'asd321';

#There is a space before 'identified' which is invisiable on the book. It confuses me a lot.

5.quit;#Exit from MySQL toolkit.

6.use bank; #Use the database created just now;

7.mysql -uvcsql -pasd321;#LogIn


2.Some Functions

1.SELECT Now();#Display Time

2.SHOW CHARACTER SET;#Describe the character set

3.


3.Create a table named 'person'

CREATE TABLE person

(person_id SMALLINT UNSIGNED,

 fname VARCHAR(20),

 lname VARCHAR(20),

 gender CHAR(1),

 birth_date DATE,

 street VARCHAR(30),

 city VARCHAR(20),

 state VARCHAR(20),

 country VARCHAR(20),

 postal_code VARCHAR(20),

CONSTRAINT pk_person PRIMARY KEY (person_id)

);

gender CHAR(1) CHECK (gender IN ('M', 'F'));#Add a constraint to gender

gender ENUM('M', 'F')#replace 'gender CHAR(1)' with this

4.Create a table named 'favourite_food'

CREATE TABLE favourite_food

(person_id SMALLINT UNSIGNED,

 food VARCHAR(20),

CONSTRAINT pk_favourite_food PRIMARY KEY (person_id, food),#设置两个字段的复合主键

CONSTARINT fk_fav_food_person_id FOREIGN KEY (person_id)#设置索引,将本表(favourite_food)的person_id字段关联到person表的person_id字段,作为外键,此处有大坑,在后面将恶心我好久

 REFERENCES person (person_id)

);

5.Check tables

desc person;

desc favourite_food;

6.把主键'person_id'改为自增主键

ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;

#雾草,这里这个大坑,因为之前在favourite表中,已经将本表内复合主键person_id关联到person表的person_id字段作为外键。有点绕。简单地说,就是想要修改的字段,已经被关联作为另一张表的外键了。所以不能随便修改。想要修改,必须先解除外键关系,修改好后,再重新关联外键。

处于数据库安全角度考虑,在解除外键并修改过程中,要将表锁定(LOCK),修改好后,解锁(UNLOCK)。这里坑我好长一段时间,一直报错。

键入ALTER*后


Chapter 2_第1张图片
ERROR1833

意味着不能这样修改,经搜索后,得到这样一个解决方案:

ERROR1833-Stackoverflow

但是尝试n次后,并不奏效,并一直报错,其中有几次经检查后,是自己代码键入错误,尴尬~!当时检查重拼后,仍有错误,看来是这个解决办法中的代码有问题。

Chapter 2_第2张图片
红框中有问题代码
Chapter 2_第3张图片
ERROR 1064

分析代码可知,FOREIGN KEY (person_id)没有指定所在的表。翻阅SQL技术文档,有如下提示:ALTER TABLE Syntax

Chapter 2_第4张图片
代码可简化如下

ALTER TABLE favourite_food

           ADD CONSTRAINT fk_fav_food_person_id FOREIGN KEY (person_id)

          REFERENCES person (person_id);


外键重新添加完毕

UNLOCK TABLES;


完毕

让我看一下成果吧:

desc favourite_food;


Chapter 2_第5张图片
auto_increment

你可能感兴趣的:(Chapter 2)