码迷,mamicode.com
首页 > 数据库 > 详细

基础SQL

时间:2016-06-26 14:08:33      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

create database db_name

drop database db_name
查看mysql数据库当前状态信息
mysql>status;
 
 
1)说明:创建表
create table tb_name (col1 type1 [not null] [primary key] [auto_increment],col2 type2,...)
根据已有表创建新表
create table tab_new like tab_old
create table tab_new as select col1,col2,... from tab_old definition only
2)说明:删除表
drop table tab_name
3)说明:查看表结构/查看表
desc tab_name
show tables
4)说明:增加一个列
alter table tab_name add column col_name type
 
:列增加后将不能删除。DB2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度
5)说明:几个简单基本的sql
选择:select *from tab_name where 范围
插入:insert into tab_name (field1,field2...) values (value1,value2...)
删除:delete from table where 范围
更新:update tab_name set field1=value1,field2=value2... where 范围
排序:select *from tab_name [where...] order by field1,field2 [desc]
总数:select count(field1) as 别名 from tab_name [where...]
求和:select sum(field1) from tab_name
平均:select avg(field1) from tab_name
最大:select max(field1) from tab_name
最小:select min(field1) from tab_name
6)sql函数
a.in
select *from table1 where a [not] in (value1,value2,...)
b.between between限制查询数据范围时包括了边界值,not between 不包括
 
 
 
 
1)创建/删除索引
create [unique] index ind_name on tab_name (col...)
drop index ind_name on tab_name
索引是不能修改的,只能删除重新建
2)添加/删除主键
alter table tab_name add primary key(col)
alter table tab_name drop primary key(col)
3)创建/删除视图
create view view_name as select satement
drop view view_name
 
 
1)说明:几个高级查询运算词
a:UNION运算符 [并集]
UNION 运算符用于合并2个或多个SELECT结果集并消除重复行. [UNION ALL不消除重复行]
SELECT语句必须具有相同的数量的列,且列对应的数据类型也相同
b:EXCEPT运算符 [差集]
EXCEPT 包含在table1不在table2中并消除重复行的一个结果集[EXCEPT ALL不消除重复行]
c:INTERSECT运算符 [交集]
INTERSECT两个table中都有且消除重复[INTERSECT ALL不消除重复行]
2)说明:使用外连接
a.left (outer) join  
左表为驱动表,右表为匹配表
b.right (outer) join
c.full/cross (outer) join
eg: A left join B on... where B.id is null
    内连接:完全满足 on 后面的调节匹配的才会显示
3)说明:两张关联表,删除主表中已经在副表中没有的信息
delete from table1 where not exists (select *from table2 where table1.field1=table2.field1)
 
4)分组:Group by:
把查询结果集分成小组 ,之后的分组函数以小组为单位执行
在select指定的字段要么就要包含在Group By语句的后面,作为分组的依据;要么就要被包含在聚合函数中。
5)having
用于指定过滤条件.分组函数参与的过滤条件必须写在
HAVING子句里,WHERE不支持。
 
6)分页查询
oracle   rownum
mysql  limit
//eg:查询工资最高的前5条数据
select empno,ename,sal,rownum from (
select empno,ename,sal from emp order by sal desc
)
where rownum<=5;
 
 
SQL函数
1)聚合函数(分组函数)
max()  min()  avg()  sum()  count()

基础SQL

标签:

原文地址:http://www.cnblogs.com/laseine/p/5617744.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!