mysql 总结一(基本语句)

来源:互联网 发布:北京80越野车数据 编辑:程序博客网 时间:2024/05/20 15:40

一、mysql数据库基本语法

1.登录mysql数据库

语法:mysql -u 登录名 -h IP地址(远程连接数据库,本地数据库不用) -p 密码;

例子:mysql -u root -h192.168.0.233 -p 按enter键 输入密码(远程登录)

        

           mysql -u root -p 按enter键 输入密码(远程登录)

          

2.操作数据库

   a.显示数据库列表

     语法:show  databases;

     例子:show databases;

      

  b.创建/删除 数据库

   语句:create database 数据库名;

              drop database 数据库名;

  例子:create database dataone;(创建名为dataone的数据库)

c.选中某个要操作的数据库(即选中数据库)

语句:use 数据库名;

例子:use dataone;(选中名为dataone的数据库)

d.查询选中的数据库中的表

语句: show tables;

例子: show tables;(若数据库显示empty set等,表示该数据库没有表);

E.查看某个表的结构(字段)

语句:desc 表名;

例子:desc student;(查看表名为student的字段)


三、对某个数据库中表的操作(在选中某个数据库后的操作)

1.创建表

 语句:create table 表名(column1(字段一) kind(类型) [not null(不能为空)] [primary key(为主键)],column2(字段二) kind(类型) [not null(不能为空)] [primary key(为主键)]);

例子:create table student(id bigint not null primary key,name varchar(6) null,age smallint null);(创建名为student的表,有字段id(主键),name,age)

2.删除表

语句:drop table 表名;

例子: drop table teacher;(删除名为teacher的表)

3.给某个表添加字段

语法:alter table 表名 add column 字段名 type(类型);

例子:alter table student add column class varchar(20);

4.为某个表删除字段(没有索引情况下,即如上图key 为空)

语句:alter table 表名 drop column 字段名;

例子:alter table student drop column class;

5,为某个表删除主键约束

语句:alter table 表名 drop primary key;

例子:alter table student drop primary key;


6,为某个表添加主键约束

语句:alter table 表名 add primary key (为主键的字段);

例子:alter table student add primary key(id);

7.为某个表添加外键字段

语法:alter table 子表名 add [constraint 约束名(删除约束用到)] foreign key(外键字段) references 父表名(父表中与子表的外键对应的字段) ;子表名(要添加外键的表),父表名(没有外键的表)

例子:alter table student add constraint stu_tea_id foreign key(teacher_id) references teacher(id);(student表中字段teacher_id对应teaher表中id字段)

8.为某个表删除外键字段

语法:alter table 表名 drop foreign key 约束名;(这里是约束名,不是字段名,后面会显示怎么查询约束名)

例子:alter table student drop foreign key stu_tea_id;


0 0
原创粉丝点击