常用的sql语句

2025-11-05 10:03:56

1、一、数据库操作

1、说明:创建数据库

CREATE DATABASE 数据库名

2、说明:删除数据库

drop database 数据库名

3、选择数据库

USE 数据库名

二、表操作

1、说明:创建新表

create table 表名(列名 类型 [not null:非空] [primary key:主键] [auto_increment:自增] [comment:备注],col2 type2 [not null],..)

2、根据已有的表创建新表: 

create table 新表名 as select 列名1,列名2… from 旧表名 

3、说明:删除新表

drop table 表名 

4、说明:增加一个列

Alter table 表名 add column 列名 类型

注:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。

5、说明:添加主键: Alter table 表名 add primary key(列名) 

说明:删除主键: Alter table 表名 drop primary key

6、外键约束

alter table 外键表名 add constraint 约束名称 foreign key (外键字段) references 主键表名(约束列名)

7、说明:创建索引:create [unique] index 索引名 on 表名(列名) 

删除索引:ALTER TABLE 表名 DROP INDEX 索引名

8、说明:创建视图:

CREATE VIEW 视图名 AS 

SELECT 列名

FROM 表名

删除视图:DROP VIEW 视图名

三、说明:几个简单的基本的sql语句

选择:select * from 表名 where 范围

插入:insert into 表名(列名,列名) values(value1,value2)

删除:delete from 表名 where 范围

更新:update 表名 set 列名=value1 where 范围

查找:select * from 表名 where 列名 like ’%value1%’

总数:select count(0) as totalcount from 表名

求和:select sum(列名) as sumvalue from 表名

平均:select avg(列名) as avgvalue from 表名

最大:select max(列名) as maxvalue from 表名

最小:select min(列名) as minvalue from 表名

升降序

默认情况下,它是按升序排列。

升序 SELECT * FROM  表名  ORDER BY field ASC

降序 SELECT * FROM  表名  ORDER BY field DESC

分组 select 列名 from 表名 group by 列名

分页 select 列名 from 表名 limit Index(起始页数索引),page(显示几条数据)

子查询(表名1:a 表名2:b)

select 列名 from a where a IN (select 列名 from b ) 或者: select a,b,c from a where a IN (1,2,3)

外连接查询(表名1:a 表名2:b)

select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

内连接查询(表名1:a 表名2:b)

select a.a, a.b, a.c, b.c, b.d, b.f from a inner JOIN b ON a.a = b.c

2、添加约束

alter table 添加约束表名 add constraint 约束名称 约束类型 (约束字段) 

删除约束

alter table 表名 drop constraint 约束名

所有约束通用格式。

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢