码迷,mamicode.com
首页 > 数据库 > 详细

SQL语句基本语法

时间:2017-05-16 23:11:54      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:sql

首先写入可显示中文代码

set character_set_client=gbk;
set character_set_results=gbk;

或只输一句  

set names gbk;

创建数据库

create database 库名;

查询现有数据局

show databases;

删除数据库

drop database +库名

使用库

use 库名;

创建表

create table Student(
     id int,
     name varchar(20) not null,
     age int,
     sex  char(2) not null;
     major varchar(20)
);

以学生表为例,创建主键自增表

creat table student(
     id int primary key auto_increment,//注:只有int类型且为primary key 才可以使用auto_increment.
     name varchar(20) not null,
     banji varchar(20) not null,
     banji integer default(1),  //设定默认值为1
     );

创建表后添加设定或改变默认值

例如:

alter table student modify score int;
alter table student modify score int default ‘1‘;

主键约束 

创建表时添加主键约束

creat table person(
    id int not null,
    name varchar(20) not null,
    adress varchar(50),
    primary key(id)
);

创建表后添加主键约束

alter table person add primary key(id);

外键约束

create table Score(
     p_id int,
     name varchar(20) not null,
     age int,
     sex  char(2) not null;
     major varchar(20),
     foreign key(p_id) reference persons(id)
);

创建表后添加外键约束:

alter table 表名 add foreign key (p_id) references 主表名 (id)

创建主外键关系约束

alter table score add foreign key(p_id) reference person(id);
check
banji int (banji between 1 and 3)


查询表

show tables;

在表中添加字段(就是添加各种想要的属性)(比如这里在student表中添加score)

alter table student add score double;

即 alter table 表名 add 字段 字段类型;

添加完字段后可以   查询表结构

desc Student;

即 describe 表名; 或 desc 表名;

修改表名

alter table 原表名 rename to 新表名;

修改字段名(属性名)

alter table 表名 change 原字段名  新字段名 原数据类型;
alter table student change physics physisc char(10) not null;

//注:只有int类型且为primary key 才可以使用auto_increment.

修改属性(即修改修饰这个字段的数据类型)

alter table student modify score int;


即alter table 表名 modify 字段名 数据类型;

删除一列

alter table 表名 drop 字段名

 

删除一条记录

delete  from student where score<60;
delete  from student where name=xiaohong;
delete from student where name="zhangsan" and major="yingyu";

(比如表中有两个都是zhangsan,并且没设置id为主键的话id也都是1,但是两人专业不一样,删除的时候就要加上两个条件,否则同名的都会被删除)


添加一条记录

insert into student(id,name,age,major)values(1,‘张‘,20,80);
insert into student(id,name,age,major)values(1,"张三",20,"安卓");

(添加完可以)查看表内内容

select * from 表名  
select name from student where id=1;

多表查询

select 表名.字段名 from 表1,表2... where 表1.字段=表2.字段 and 其它查询条件;

修改某一个记录(把表上id号为1这条记录上的sex这个字段内容改为女)

update people set sex=‘女‘ where id=1

排序

select * from 表名 order by 字段名 desc;
select * from 表名 order by 字段名 asc;

修改固定词

inser into like ‘宋_‘


SQL语句基本语法

标签:sql

原文地址:http://lvshihai.blog.51cto.com/4732144/1926327

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!