SQL常用语句大全

创建用户create user ‘用户名’@‘%’ identified by ‘密码’    (%处填%表示远程连接 localhost表示只能在本机登陆 也可以填ip )

赋予最高权限grant all on *.* to ‘user’@‘%’;

使更改立即生效 flush privileges;

查看当前用户 select user() ;

查看当前数据库 select database() ;

创建数据库 create database [if not exist] 数据库名

查看有哪些数据库 show databases;

删除数据库 drop database [if exists] 数据库名

创建表 create table [if not exists] 表名(

Id int,

name char(10),     ##char 定长字符

sex varchar(10)     ##varchar 不定长字符

建表实例

 1 CREATE TABLE Teacher
 2 (
 3 tNo varchar(255) NOT NULL,
 4 tName varchar(255),
 5 tSex char(1),
 6 tBirthDate date,
 7 tSalary decimal,
 8 tHairDate date,
 9 depNo varchar(255),
10 PRIMARY KEY (tNo),
11 CHECK (tSex="男" OR tSex="女")
12 );

查看有哪些表 show tables

查看表结构 desc 表名

           show create table 表名

删除表 drop table 表名

表中数据的增删改查

*增

insert into 表名 value();

insert into 表名 (id字段名) vaue();  #添加时给特定字段赋值

insert into 表名 values (),(),()…  #一次添加多条数据

insert into 表名 set 字段1 =value 字段2 =value…

*删

delete from 表名 where 条件

*改

update 表名 set id = value where 条件;

*查

select * from 表名

查询所有  select * from 表名

查询单列  select 字段名 from 表名

查询指定条件的内容  select * from 表名 where 条件

查询时为列指定别名  select stu_id as 学号 from student

                          select stu_id as 学号,stu_name as 姓名 from student

模糊查询         select * from student where stu_name like ‘y%’  ##(查询以y开头的数据)

                  select * from student where stu_name like ‘%y%’  ##(查询含有y的数据)

查询时排序        select * from student order by stu_id asc  (desc倒序,asc正序)

查询时限制显示数据的数量 select * from student limit 100(限制输出的条数)

 

聚合函数       select MAX(stu_age) from student   常见函数(MAX()最大值MIN()最小值SUM()求和AVG()平均Count()统计ROUND()四舍五入

分组查询       select dep_id as 学院代码,count(dep_id) as 人数 from student group by dep_id;

增加条件       select dep_id as 学院代码,count(dep_id) as 人数 from student group by dep_id having 人数 = 1;

更改表结构 

Alter table tbname modify id char not null ##更改字段类型和约束

常见约束  

not null 非空约束;

unique key 唯一约束;

primary key 主键约束;

auto_increment 自增长;

default xxx 默认值

Alter table tbname rename newname  ##更改表名

Alter table tbname change 字段名 newname  ##更改字段名

Alter table tbname add sex varchar(10)  ##增加字段

Alter table tbname add sex varchar(10) first\after** ##添加时设置字段添加的位置

Alter table tbname add unique key(字段名)  ##给指定字段添加键

Alter table tbname drop                     ##删除字段

Alter table tbname drop key name      ##删除键

表关联

Constraint keyname foreign key(内部字段名) reference 外表名(外表字段)

猜你喜欢

转载自www.cnblogs.com/yinqingzheng/p/10033015.html
今日推荐