SQL语句小结

1、创建数据库

      create database 数据库名

2、删除数据库

drop  database 数据库名

3、创建表

1>、create table 表名 (col1 type1 [not null] [primary key],col2 type2 [not null]....)

2>、create table tab_new  like tab_old(使用旧表创建新表)

4、增加一个列

alert table tabname add  column col type

5、添加/删除主键

alert table tabname add/drop primary key(col)

6、创建索引

create [unique] index idxname on tabname(col...)

7、创建视图

create view viewname as select statement

8、基本sql语句

查询:select * from table1 where 范围

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

删除:delete from table1 where 范围

更新:update table1 set field=value where 范围

模糊查询:select * from table1 where field1 like '%value1%'

排序:select * from table1 order by field1,field2 [desc]

总数:select count as totalcount from table1

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

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

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

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


9、几个高级查询运算符

union运算符(联合查询)

(select *from tab1where....) union (select *from where...)

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

(SELECT * FROM TableA) EXCEPT (SELECT * FROM TableB)

distinct运算符

select distinct xing, ming from B(因为Distinct是作用于多列的,也就是说必须要xing和ming 全都相同的才会被剔除)

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

SELECT * FROM TableA INTERSECT SELECT * FROM TableB

10、多表连接

inner join

select tClassName,tSName from TblClass  inner join tblstudent on TblClass.tClassId=TblStudent.tSClassId

(只有两个表中的数据符合on条件,才会显示在结果集中)

left join(左表中的信息全部出现,右表中的信息必须能够匹配的才出现未匹配的项使用null填充)

right join(右表中的信息全部出现,左表中的信息必须能够匹配的才出现未匹配的项使用null填充)

full/cross join(所有数据都会出现,不匹配的项使用null填充只要想做连接查询,必须分析出两个表间的关系)

11、子查询

select *from tab1 where id in(select id from tab2 where....)括号中的sql语句则为子查询

12、多表查询

select tab1.*,tab2.* from tab1,tab2 where tab1.[字段]=tab2.[字段]

13、分组:group by

1>、 错误的,where中不能出现分组函数

select d.name , avg(e.salary) from s_dept d, s_emp e where d.id = e.dept_id group by d.name and avg(e.salary) > 1000;

2>、正确, having 紧跟 group by

select d.name , avg(e.salary) from s_dept d, s_emp e where d.id = e.dept_id group by d.name having avg(e.salary) > 1000;

 14、as用法

select 字段 as 别名

 

posted @ 2017-07-10 17:22  根须  阅读(127)  评论(0)    收藏  举报