您的位置:首页 > 数据库

数据分析-SQL-基础篇

2019-04-06 21:31 113 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/weixin_44778063/article/details/89060657

----------------------------------------写在前面----------------------------------------

适用情形

MySQL、SQLServer、Excel…

书写规范,以MySQL为例

  • 支持中文
  • 不区分大小写(有的区分)
  • 字符串要用单引号,如’string’
  • 数字也可以加单引号,如’4’
  • 木有撤销功能,所以操作前记得备份
  • 符号一律在英文格式下输入
特殊符号
  • ‘N’

    表示以Unicode格式存入数据库,使用2个字节存储字符
  • 如N’string’
  • ‘@’

      标识本地的变量或者参数
  • ‘#’

      标识临时表或过程
  • ‘##’

      标识全局临时对象

    -----------------------------------简单查询----------------------------------------

    1. 条件查询

    --多字段、多条件全查
    select 字段1,字段2 as 别名 from 表名 where 条件1 and/or 条件2    --as关键字可以省略
    select * from users where ojbk = 'you'
    
    --区间查询
    select * from 表名 where 字段 between 范围1 and 范围2
    --包括边界值,not between不包括
    select * from 表名 where 字段 in('元素1','元素2','元素3')
    
    --模糊查询
    select * from 表名 where 字段 like '%关键字%' or '%关键字' or '关键字%'
    
    --空值查询
    select * from 表名 where 字段=''
    select * from 表名 where 字段 is Null

    2. 聚合函数

    select max(字段) from 表名
    select min(字段) from 表名
    select avg(字段) from 表名
    select sum(字段) as 别名 from 表名
    select count(字段) as Totalcount from 表名
    
    /*聚合函数常与以下的分组函数一同使用*/

    3. 排序、分组、分页

    select * from 表名 order by 字段 asc
    
    select 字段1,聚合函数(字段2) from 表名 group by 字段
    --分组条件查询
    select 字段1,聚合函数(字段2) from 表名 group by 字段 having 组条件
    --having兼容where
    
    --分页查询
    select * from 表名 limit int类型数据1,int类型数据2
    /*数据1指从下标为?的行开始(从0计),数据2指当前分页显示?条数据
    只有一个数据时,则当前分页从0行开始,显示?条数据*/
    
    --简单的组合查询(顺序不可调动)
    select * from 表名 where 条件1 and 模糊条件2 order by 字段 desc limit 0,4
    --子条件查询(将一个查询结果当做条件使用)
    select * from 表名 where 字段=(select 字段聚合函数 from 表名)
    select a,b,c from a where a IN (select d from b)

    4. 多表联合

    --建立关联表
    /*表1和表2有相同字段的,如字段1,需标注表1.字段1或表2.字段1,否则可省略表名*/
    
    select 表1.字段1,表2.字段1,字段2,字段3, from 表1,表2 where 表1.字段1=表2.字段1
    
    --左连接查询
    select * from 表1 left join 表2 on 表1.字段1=表2.字段1
    /*以左表为准,右表数据匹配,无匹配数据则过滤,左表以Null填充*/
    
    --右连接查询
    select * from 表1 right join 表2 on 表1.字段1=表2.字段1
    
    --内连接查询
    select * from 表1 inner join 表2 on 表1.字段1=表2.字段1
    
    --全连接
    select * from 表1 FULL JOIN 表2 on 表1.字段1=表2.字段1
  • 内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
    标签: