数据库常用sql整理

来源:互联网 发布:现在什么软件翻墙好 编辑:程序博客网 时间:2024/06/05 00:41

1、 创建数据库:create database database-name

2、 删除数据库:drop database dbname

3、 创建新表:create table tabname(col1 type1[not null] [primary key],col2 type2 [not null],……)

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

(1):createtable tab_new like tab_old(使用旧表创建新表)。

(2):create table tab_new as select col1,col2……from tab_old definitiononly

5、 删除新表:drop table tabname

6、 添加主键:alter table tabname add primarykey(col)

7、 删除主键:alter table drop primary key(col)

8、 创建索引:create [unique] index idxname ontabname(col)

9、 删除索引:drop index idxname   注:索引是不可更改的,想更改必须删除重新建。

10、查询:select * from table1 where 范围

11、插入:insert into table1(field1,field2) values(value1,value2)

12、删除:delete from table1 where 范围

13、修改:update table1 set field1=value1 where 范围

14、模糊查询:select * from table1 where field1 like ‘%value1%’

15、排序:select * from table1 order by field1,field2 [desc(降序) 或 asc(升序)]

16、总数:select count(1) as totalcount from table1

17、求和:select sum(field1) as sumvalue from table1

18、平均:select avg(field1) as avgvalue from table1

19、最大:select max(field1) as maxvalue from table1

20、最小:select min(field1) as minvalue from table1

21、几个高级查询运算符:

(1)union运算符:返回两个结果集的并集。

(2)except 运算符:返回两个结果集的差(即从左查询中返回右查询没有找到的所有非重复值)。

(3)intersect运算符:返回两个结果集的交集(即两个查询都返回的所有非重复值)

22、使用外链接:

(1)left join 

(2)right join

注:本人博客中已总结left jion、right join以及inner jion 的区别,这里暂不做解释。

23、分组:group by

24、前10条记录:select top 10 * from table1 where 范围

25、Mysql查询按姓氏拼音排序:SELECT * FROM tab1 ORDER BY CONVERT(name USING GBK)

26、选择从10到15的记录:select top5 * from (select top 15 * from table1 order by id asc) table_别名 order by id desc

 

1 0
原创粉丝点击