java学习-sql语句

一些简单的关于SQL语句的总结。


SQL指结构化查询语言。

SQL语句对大小写不敏感。

索引:索引于表相当于目录于书。索引表是与基本表关联的一种数据结构,它包含由基本表中的一列或多列生成的索引键和基本表中包含各个索引键的行所在的存储位置。不论基本表中是否按索引键有序,但索引中总是按索引键有序的。

select语句执行顺序:from - where - group by - having - select - order by


1.创建数据库:CREATE DATABASE dbname

2.删除数据库:DROP DATABASE dbname

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

4.删除新表:drop table tbname

5.更改表:alter table tbname

(1)增加一个列:alter table tbname add column colname type
(2)添加主键:alter table tbname add primary key(colname)
(3)删除主键:alter table tbname drop primary key(colname)
(4)添加列:alter table tbname add colname type
(5)删除列:alter table tbname drop column colname

6.创建索引:create [unique] index idxname on tbname(col…)

7.删除索引:drop index idxname

8.创建视图:create view vname as select statement

9.删除视图:drop view vname


10.查询:
一般语句:select * from tbname (where condition1 and condition2)
查找消除取值重复的行:select distinct sno from tbname
查找条件模糊或者字符匹配的字段:
select * from tbname where sname like '王%'【sname为姓名,% 代表任意长度(长度可以为0)的字符串】
select * from tbname where sno like '13_0322'【sno为学号,_ (下横线) 代表任意单个字符】

11.插入:
insert into tbname values (value1,value2,…)
insert into tbname (col1,col2,…) values (value1,value2,…)

12.删除:delete from tbname where condition

13.更新:update tbname set colname=value where condition

14.排序:select * from tbname where condition order by colname [asc|desc]【升序|降序】

15.输出结果(前n行):select (top n) sno,sum(grade) as ‘总分’ from tbname【sno为学号,grade为成绩】
查询结果集输出到新表中:select sno into newtbname from tbname where condition


16.集合运算:UNION(并),INTERSECT(交),EXPECT(差)

如:select sname from tbname1 where condition1 UNION select cname from tbname2 where condition2【满足表一中条件一并且满足表二中条件二的】

17.简单分组查询:

select sex,count(*) as ‘人数’ from tbname where condition group by sex [having condition]
select sno,avg(grade) as ‘avg of score’ from tbname where condition group by sno having avg(grade)>60 order by ‘avg of score’

18.两表联查:select * from tbname1 full (outer) join tbname2 on joincondition[e.g. tbname1.a=tbname2.c]

19.子查询:select sname from tbname1 where sno in (select sno from tbname2 where condition)