SQL 基础知识 速查手册

本文为了阅读和书写方便使用了小写,SQL不区分大小写,但是工程师需要标准书写。
0、登录
      命令:mysql -u root -h 10.161.24.231 -p 
               unicom123
      帮助:  help 
      注释:--  单行注释 或 /*多行*/
      oracle数据库不支持as,去掉as即可。
1、数据库操作
     查看: show databases;
     建立:create dababase db;
     使用:use db;
2、表的操作
    查看:show tables;
    创建:create table st
               (
                  mkey   char(10)  not null,
                  c1        varchar(100)  ,
                  c2        int,
                  primary key(mkey)
                );
     *定义各列,并设置表约束。、
      常见约束:
      主键约束:非空、唯一。
      唯一约束:unique
      非空:not null
      默认值;default 0;
      类型:char varchar int integer date
      查看表结构:desc st;
      修改-添加列
              alter table st add column (addc  int not null);
      修改-删除列;
              alter table st drop column addc;
      插入数据:
              insert into st values("01","wang",100);
              insert into st values("02","wang2",null);
             *空值用Null代替,主键不能为空。
      查询:select
      重命名:rename table st to st2;
      删除:drop table st2;
3、基本查询规则
     基础查询:select xuehao,score from st1;
     设置别名: select xuehao as c1,score as c2 from st1;
     常数查询:select "zuche" as changshu,xuehao as c1 from st1;
                     select 'haha' as h,xuehao from st1; 
     查询结果去重复: select score from st1;
                               distinct:区别的、不同的、不重复的
                               select DISTINCT score from st1;
                               select DISTINCT score,date from st1;
                              *以结果行为标准 去除重复。
      条件:where
                select * from st1 where score >=99;
      算术运算:
      >1:+ - * /
                select score*2 from st1 where score >=99;
                select score*2 as sc2 from st1 where score >=99;
      >2:=  <>  >= <=
                select * from st1 where score <>99;
      >3:表达式
                select * from st1  where score*2>100;
      >4:字符串按字典顺序比较 :即 “1”<"11"<"2"
                select * from st1 where  name >"w" && name <"z";
                +----------+------+-------+------------+
                | xuehao   | name | score | day        |
               +----------+------+-------+------------+
                | 20180103 | wang |   100 | 2010-01-01 |
               +----------+------+-------+------------+
       >5: IS NULL  IS  NOT NNULL
                select * from st1 where name is not null;
                select * from st1 where name is null;
       >6: AND OR () 条件运算
                select * from st1 where name is not null and  score >90;
4、聚合查询(除*号外,将自动排除列值为NULL的行)
     【1】函数:count() 统计行数  sum 求和 avg 平均值 max  min 极值
                      select count(*),max(score),avg(score) from st1;
     【2】排重distinct
                      select count(distinct score) from st1;
5、分组查询
     【1】group by
                      select * from st1 group by score;
     【2】having 条件 
                      对分组后的数据指定条件 
     【3】区别:
             where用于指定行的条件,其条件可包含任意列,但不能包含聚合函数。
             select name as c1 from st1 where name<>"wang";
             having 用于指定组条件,且列的条件必须来自group的列或select 列,可以使用聚合函数。
             select day  as c1 from st1 group by score having score<120;来自group by 执行正确。
             select name as c1 from st1 group by score having name<>"wang"; 来自select 执行正确。

            select day  as c1 from st1 group by score having name<>"wang";

            //执行错误; Unknown column 'name' in 'having clause'

            二者都不能用别名。
       【4】使用聚合函数:select * from st1 group by score having count(score)>2;
6、排序查询
         order by :select * from st1 order by score;
         降序desc:select * from st1 order by score desc;
         升序asc:select * from st1 order by score asc;
         使用聚合函数:
         /*按个数排序*/select *,count(score) from st1 group by score order by count(score) desc;
         可以使用别名:select *,count(score) c1 from st1 group by score  order by c1;
7、数据操作
  【1】插入数据:  (列清单)==(值清单)
      格式:insert  into st1 (列x,列y,..)  values(值x,值y,..);
 默认时,需全部值且必须按顺序输入,空用NULL代替。
      insert into st1 values("21321332","qeare",80,"20130203");
 列项输入,无需全部输入且按列清单顺序输入,但默认自动填充NULL。
 insert into st1 (xuehao,score) values("21321432",65);
  【2】设置默认值
       方法1:利用约束设置。
  create table st 
       (
           name char(10) not null,
           score int default 0
       );
       insert into st (name) values("ZHANGSAN");
  方法2:插入设置。
  insert into st  values("ZHANGSAN",default);
  错误:值不会被设置默认值而是null。
  insert into st  values("ZHANGSAN",null);
  【3】复制数据 insert select 
       create table st2 ( name char(10) not null,jishu int);
  insert into st2 (name,jishu) select name,score from st where score is not null;
  *原理:遍历使用select来生成值清单。
  【4】删除数据(按行删除)---delete from table where cond;
        删除部分数据:
delete from st1 where name is null;
删除全部数据:truncate st2;
删除全部数据和表:drop table st;
  【5】修改数据
       update st1 set day="20130102";    
       update st1 set score=60 where score is null;   
  --  多列修改
  update st1 set name="ddas",score=121 where xuehao=20180204;
  【6】事物
   原子性 独立性 多条SQL执行不被打断。
   start transaction
         insert/delete/update/
...
   commit/rollback;
   注意:不同数据库事物开始语句不同,Oracle可省略。
         commit 执行后,SQL结果会保存。
rollback,可撤销/回滚SQL执行结果,不保存。
8、复杂查询:
  【1】视图理论:
   原理:视图保存的是一条select语句,当查询时会临时创建一个临时表。该表不做任何存储。
         视图的目的在于简化操作、安全等等但不会加快查询速度。
视图之上创建视图->多重视图严重影响效率。
   限制条件:
         (1)视图数据无顺序性,多数系统不支持group by 语句。
(2)限制更新操作
     原理:无法保证视图数据与实际表之间数据的一致性!
 可更新需满足条件:未使用distinct,from只有一张表,未使用group by  having语句。
  【2】视图操作:
       创建:creat view 视图名(视图列1,视图列2...) AS select (对应列1,列2...) from ...
             create view v(name,num) as select name,xuehao from st1;
  使用: select * from v;
  删除:drop view v;
 【3】嵌套查询/子查询
      从查询结果中再查询:
 格式:select ..from (嵌套子查询语句) [as] 子查询生成结果存放的临时表
 select * from (select name from st1) as st2;
 注意:mysql可省略as,oracle不支持as.
 【4】标量查询
      标量:查询结果只能一行一列,即是标量。
 原理:在查询语句中会先执行标量查询语句,计算这个标量,然后带入到查询语句中执行。
 select name,score from st1 where score>(select avg(score) from st1);
 分解执行:
    1.select avg(score) from st1;
         2.select name,score from st1 where score>164;
 select name,score,(select avg(score) from st1) from st1;
 分解执行:
    1.select avg(score) from st1;
    2.select name,score,164 from st1;
  【5】关联子查询
       关联原由:子查询语句引用了外部查询语句的表。
  select name,score from st1 a where score>(select avg(score) from st1 b where a.day=b.day group by day);
  格式:定义:数据表 别名  引用:别名.列名 
  【*】标量查询、关联子查询每条记录都要执行一次子查询,比较消耗资源。
9、函数(根据不同数据函数名称/定义不同)
   算术函数:abs mod round
   字符串函数:拼接concat、长度length、lower\replace
   日期函数: select current_time;/*返回当前时间*/
   转换函数:
   cast:类型转换:select cast(xuehao as signed int )from st1;
   coalesce:将null转换成其他值。
   select coalesce(name,"noname") from st1;
10、谓词
   【1】like
        需使用模式匹配 %代表0及以上字符  _代表一个字符
select * from st1 where name like "g%";
select * from st1 where name like "gan_";
   【2】between  and
   select * from st1 where score between 100 and 160;
   【3】 is null is not null
   【4】in  not in
        in(值1,值2..) 数据为值1或值2或..
not in  否之。 
select * from st1 where score in(121,158);
应用到子查询:!只能有一列。
select * from st1 where score in (select score from st1 where score>190);
   【5】exists not exist 是否存在记录
11、CASE表达式 分情况查找
    类似于宏,当一行表达式满足when的一个条件时,则执行此表达式。
    select case when 条件 then 表达式
           when 条件 then 表达式
...
else 表达式
end as somename  from table;
select case 
          when score>150 
  then concat(xuehao,name)  
  else concat(name,xuehao) 
end 
as testcase from st1;
12、集合运算(针对列的操作) 
    集合运算时select两端 列数、类型必须一一对应。
加法:UNION
特点:列数、类型必须一一对应,order by 只能放在最后一条语句。
select xuehao from st1 union select xuehao from st2 order by xuehao;
特点:没有重复的数据
全加: union all
特点:显示重复的数据,显示全部数据。
交集:intersect
差集:except
13、连接操作(针对行的操作)
    内连接:根据连接条件,两张表格分别提取各自数据把符合连接条件的数据拼接组合成一张表格。
连接条件使用ON.
select * from st1  inner join st2 on st1.xuehao=st2.xuehao;
外连接:保留主表的全部数据,提取附表的数据,把符合连接条件的数据拼接到主表上,其余用NULL补充。
主表选择使用:left\right 关键字。
select * from st1  right outer join st2 on st1.xuehao=st2.xuehao;
select * from st1  left outer join st2 on st1.xuehao=st2.xuehao;
交叉连接:cross join 或默认省略
多表连接:配合使用别名完成多表连接操作。 
14、窗口函数(OLAP函数)
    格式:<窗口函数> over ([partition by 列清单]  order by 排序列)
窗口函数有:聚合函数,专用函数(RANK 等)
原理:窗口函数是在select执行结果后执行的,是对查询结果的呈现。
Rank() 函数:
    partition决定操作范围,order排序方式。
select *, rank() OVER(partition by day order by score) as ranking from st1;/*mysql不支持*/
*放在高级SQL高级部分。
15、grouping运算符(超组)
    用于group by 配合使用,完成其不具备的聚合功能。
此功能在于会将所有group by 列的结果都执行聚合效果。
弥补了使用group by 语句后不能对分组和全局一并聚合操作的缺点。
roolup:合计行函数
select name,sum(score) as zongfen from st1 group by roolup(day);
等效于:select name,sum(score) as zongfen from st1 group by ();
       select name,sum(score) as zongfen from st1 group by day;
grouping 函数,将Null置0,其余为1.
cube:积木函数 等。
16、Java连接MySQL方法
    1.import jdbc 包
2.定义:
连接对象:connect 
执行声明:statement 
返回结果:resultset
    3.加载驱动:class.forname(驱动名);
4.获取连接:con==getconnet..(uRL,usr,password);
      创建声明:con.creates..
    5.执行SQL:result==executexxx(sql...)
6.分析结果:result.getxxx("id")
7.关闭:结果-》声明-》连接 close顺序
17、存储过程与触发器
    存储过程是预编译的,执行速度较快.
语法:DELIMITER分隔符,防止SQL语句被执行.
格式:
DELIMITER //
    CREATE PROCEDURE  过程名([[IN|OUT|INOUT] 参数名 数据类型[,[IN|OUT|INOUT] 参数名 数据类型…]]) 
[特性 ...] 
    begin
SQl...
end
    DELIMITER 
触发器:当插入更新时触发执行一段SQL语句,可在事件之前或之后执行.
Create trigger triggerName
    After/before insert/update/delete  //定义触发条件 
on 表名  
    For each row #这句话是固定的
    Begin
    Sql语句; # 一句或多句,insert/update/delete范围内
    End;
    删除触发器:
    Drop trigger 触发器名
    查看触发器
    Show triggers
18、索引
  索引属于数据库高级部分。
  【1】概念
    索引会占用一定的空间。
优势:当wherei条件查询时,没有索引,查询数据会全表遍历,有索引会直接跳转。
特点:经常被查询的主键、外键、分组的列可以建立索引。
     频繁更新的列、多重复、数值小长的列不建议建立索引。
    聚集索引:建立索引后,插入数据表会重新排序,存储记录是连续的,像字典。
非聚集索引:插入数据值记录指针,数据不连续,像指针表。
单列索引:只有一列
组合索引:多个列
全文索引:
按索引建立方式分类:B-tree、HASH、位图索引等。
  【2】建立索引
    SQL server方式:
CREATE [UNIQUE][CLUSTERED | NONCLUSTERED]  INDEX  index_name  
    ON {table_name | view_name} [WITH [index_property [,....n]]
    说明:
       UNIQUE: 建立唯一索引。
       CLUSTERED: 建立聚集索引。
       NONCLUSTERED: 建立非聚集索引。
       Index_property: 索引属性。
Mysql方式:
CREATE INDEX IndexName ON `TableName`(`字段名`(length)) ;
ALTER TABLE TableName ADD INDEX IndexName(`字段名`(length));//普通索引
CREATE UNIQUE INDEX account_UNIQUE_Index ON `award`(`account`);//唯一索引
CREATE INDEX IndexName On `TableName`(`字段名`(length),`字段名`(length),...);//组合索引
全文索引:前面只能用length针对列的前几个字符,不能对where column lick '%xxxx%'使用。
               故建立全文索引。
     ALTER TABLE tablename ADD FULLTEXT(column1, column2);
  【3】删除索引  
    SQL server方式:
 DROP INDEX table_name.index_name;
Mysql方式:
 DORP INDEX IndexName ON `TableName`;
19、SQL执行顺序
    FROM:对FROM子句中的前两个表执行笛卡尔积(Cartesian product)(交叉联接),生成虚拟表VT1
    ON:对VT1应用ON筛选器。只有那些使<join_condition>为真的行才被插入VT2。
    OUTER(JOIN):
    WHERE:对VT3应用WHERE筛选器。只有使<where_condition>为true的行才被插入VT4.
    GROUP BY:按GROUP BY子句中的列列表对VT4中的行分组,生成VT5.
    CUBE|ROLLUP:把超组(Suppergroups)插入VT5,生成VT6.
    HAVING:对VT6应用HAVING筛选器。只有使<having_condition>为true的组才会被插入VT7.
    SELECT:处理SELECT列表,产生VT8.
    DISTINCT:将重复的行从VT8中移除,产生VT9.
    ORDER BY:将VT9中的行按ORDER BY 子句中的列列表排序,生成游标(VC10).
    TOP:从VC10的开始处选择指定数量或比例的行,生成表VT11,并返回调用者
20、数据库管理
    字符集的问题:服务器级、库级、表级、列级。
引擎设置..
权限管理:mysql数据库:user、host、table_priv
账号管理:GRANT语句或直接操作user表(不安全)
  GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;
  GRANT ALL PRIVILEGES ON *.* TO 'admin'@'192.168.100.1' IDENTIFIED BY 'PASSWORD' WITH GRANT OPTION;
查看权限、更改权限:show grant for usrname;grant; revoke;
修改密码:SET password for usrname=password("密码”);
删除账号:drop user name;
数据导入导出:
工具使用:mysqldump.exe 
数据导出:mysqldump -uroot -p -dtest  >xxx.sql
数据导入:mysql -uroot -p -dtest<xxx.sql    
附录1:redhat 安装Mysql
     检查当前系统已经安装的mysql
    rpm -qa|grep -i mysql
    删除已安装的mysql
    rpm  -e --nodeps mysql-libs-5.1.71-1.el6.x86_64
    解压缩安装文件
    tar -xvf MySQL-5.6.28-1.el6.x86_64.rpm-bundle.tar
    安装MySQL
    rpm -ivh MySQL-server-5.6.28-1.el6.x86_64.rpm
    rpm -ivh MySQL-client-5.6.28-1.el6.x86_64.rpm
    service mysql start
    修改密码:
    cat /root/.mysql_secret
    SET PASSWORD = PASSWORD('root@2018');
    FLUSH PRIVILEGES;
    支持远程访问
    支持远程访问
    GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'root' WITH GRANT OPTION;
    FLUSH PRIVILEGES;
本地YUM更新:
     http://blog.51cto.com/mrdeng/1792489
    配置YUM源服务器
    /etc/yum.repos.d
附录二:Mysql自带数据库
      information_schema:数据库对象信息
      mysql:用户信息
      performance_schema:性能表
 show VARIABLES like "character_set_client";
附录三:数据类型:建议详细学习。
       bit
  bool
  int
  bigint
  float double
  date time char 
  text:长文本
  set enum
  BLOB:二进制大对象,图片等。
附录四:官网资料
        https://dev.mysql.com/doc/refman/5.6/en/help.html
        https://downloads.mysql.com/docs/refman-5.7-en.pdf
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值