MySQL数据库基本指令

对MySQL的指令不太熟悉,在此特别整理了一下一些常用的指令:

约定:大写字母写SQL关键字和函数名,小写字母写数据库、数据表和数据列的名字。(下述代码更新不同步,部分代码未依据此约定)

1 数据库的基本操作:

(1)创建数据库

create datebase people;(people是数据库名)

(2) 删除数据库

drop database people;

(3)显示所有数据库

show databases;(注意最后面有s)

(4)选择指定的数据库,以供使用。

use people;

2.表的基本操作:(进入指定数据库后)

(1)创建表(以学生为例):

create table student(id int(11) NOT NULL DEFAULT ‘0’ PRIMARY KEY COMMENT “学生学号”,name varchar(30) NOT NULL DEFAULT ” COMMENT “学生姓名”);

更改表名:

rename table tA to tB;

(2)查看表结构:

show create table student\G

show create table student;

(3)显示所有表:

show tables;(注意最后的;)

(4)添加表字段:

alter table student add age int(11) NOT NULL DEFAULT ‘0’ COMMENT “年龄”;

(5)更改表字段:

修改字段名:

alter table student change age student_age int(11) NOT NULL DEFAULT ‘0’ COMMENT “年龄”;

修改字段类型:

alter table student modify student_age varchar(10);

(6)删除表字段:

alter table student drop student_age;

(7)插入一条记录:

insert into student(id,name)values(1,’哆啦A梦’);

(8)查询表中的数据:

select * from student\G

(9)添加唯一索引:

alter table student add unique id_name(id,name);

(10)删除表:

drop table student;

(11)添加索引:create index 索引名 on 表名(字段名);
create index phone_index on poi_contact(phone);

(12)为已创建的表添加外键

首先在表中添加外键对应的字段名:

 alter table t_student add address int;

然后添加外键:

 alter table t_student add constraint FK_ID foreign key(address) REFERENCES t_address(id);

(13)创建表时添加外键

CREATE TABLE `tb_active` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `content` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
 `user_id` int(11) NOT NULL,
 PRIMARY KEY (`id`),
 KEY `user_id` (`user_id`),
 KEY `user_id_2` (`user_id`),
 CONSTRAINT `FK_ID` FOREIGN KEY (`user_id`) REFERENCES `tb_user` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
 
(14)删除外键
先删除外键名,再删除外键字段:
删除外键名
alter table t_student drop foreign key FK_ID;
删除外键字段
alter table t_student drop column address;
 
看完基础的后,这里有一份比较全面的数据库指令提供给大家参阅:http://www.cnblogs.com/tf-Y/p/5126450.html
 

版权声明:本文为博主原创文章,未经博主允许不得转载。

 

posted @ 2015-06-10 20:35  木易·月  阅读(273)  评论(0编辑  收藏  举报