mysql学习笔记(一)

  • MySQL算是平时接触比较多的数据库,最近由于没有使用,搁置了一段时间,导致好多语法都已经生疏。趁着假期有空重新拾起来。之前在补基础的时候重新回顾了数据库SQL语法,笔记都记录在了纸质的本子上。鉴于纸质笔记携带不方便,翻阅起来也慢,所以才有了这次的记录。正好最近公司也逐渐有了MySQL的任务,多方因素下,开始整理笔记,以便日后查阅。
  • 首先介绍下sql语言,全称为(structured query language)结构化查询语言,具有定义、查询、更新和控制等多种功能,是关系数据库的标准语言。
  • sql有几种分类,分别是
    数据库操纵语言DML:用于操作数据,如select,insert,update,delete
    数据定义语言DDL:用于操作表,如create,alter,drop,rename,truncate
    数据控制语言DCL:用于操作权限,如grant,revoke
    
  • 常见查询语句的结构组成:select [distinct] {*,column 别名} from table 别名 where 条件表达式。
  • 练习:
    查询雇员表编号为10的员工:
    select empno,ename,job from emp where depno = 10;
    查询去重后的部门编号:
    select distinct deptno from emp;
    查询中对列和表添加别名,as可有可无
    select e.empno as 雇员编号,e.ename as 雇员名称,e.job as 雇员工作 from emp e where e.deptno = 10;
    查询表中所有字段,可以用*,但项目中不要随便用,效率极其低
    select * from emp;
    
  • 关于distinct:
    distinct必须放在开头,去重也可以针对多个字段,多个字段只要有一个不匹配,就算是不同的记录。
    select distinct deptno,sal from emp;
    
  • 使用in查询部门名称为sales或research的雇员姓名,工资,部门
    select ename,sal,deptno from emp where deptno in (select deptno from dept where dname = 'sales' or dname = 'research');
    
  • 使用exists查询部门名称为sales或reserch的雇员姓名,工资,部门
    select ename,sal,deptno from emp where exits(select deptno from dept where (dname = 'sales' or dname = 'research') and emp.deptno = dept.detpno);
    
  • where条件符号:
    =      select * from emp where deptno = 20
    !=     select * from emp where deptno != 20
    <,>   select * from emp where deptno > 20
    any    取任意一个,满足即可   select sal from emp where sal > any(1000,1500,3000);
    some   效果与any一样    select sal from emp where sal > some(1000,1500,3000);
    all    所有都满足成立     select sal from emp where sal > all(1000,1500,3000);
    is null 在sql语法中,null表特殊含义,不能用=null或!=null判断,要用is is not 
            select * from emp where comm is null; //comm = null会查不到
    is not null 
            select * from emp where comm is not null;//同样comm !=null 会查不到
    between x and y
            select * from emp where sal between 1500 and 3000;
    效果等同于:select * from emp where sal >=1500 and sal <=3000;
    
  • 需要进行某些值的等值判断的时候可以使用in和not in
    select * from emp where deptno in (10,20);
    select * from emp where deptno =10 or deptno = 20;
    可使用and和or关键字,可以同时出现在一个sql中,此时要注意and和or的优先级,and优先级高于or,所以一定要将or的相关操作用括号括起来,提高优先级。
    select * from emp where deptno not in(10,20);
    select * from emp where deptno !=10 and deptno !=20;
    

posted on 2022-05-08 17:50  张少凯  阅读(38)  评论(0编辑  收藏  举报

导航