Mysql database foundation statement summary

    MYSQL database practice notes

A preparatory operation
    start mysql server:
      

 net start mysql


    Close mysql server:
      

  net stop mysql


    Log client database:
     

   mysql -u用户名 -p密码

Two .DDL
    delete database
      

 drop 数据库名


    Use / switch databases
      

 use 数据库名


    Display Database
    

    show databases;


    Table View
      

  show tables;


    Create a table
  

      create table 表名 (name varchar(30),age int;socre int);


    Delete table
     

   drop table 表名


    Display table structure
    

    desc 表名


    View table creation statement
    

    show create table 表名;


    Modify the table
        to add a column:
          

 alter table 表名
            add(
                列名 类型;
                列名 类型
            )


        Increase in the first place:
          

  alter table 表名
            add 列名 类型 first;


        After the specified column is added:
      

     alter table 表名 
            add 列名 类型 after 在那一列添加;


        Modify the column type:
          

  alter table 表名
            modify 列名 新列类型


        Modify the column name:
        

    alter table 表名
            change 原列名 新列名 列类型


        Delete Column:
          

  alter table 表名
            drop 列名


        Modify the table name:
      

      alter table 表名
            rename to 新表名;
            


Three .DML    
    insert data
      

  INSERT INTO user(Name,age,socre)VALUES('lisi',18,19);
        insert into user(name,age,socre)values('wangwu',45,34);
        insert into student values ('itcast_001','zhangsan',15,'nv',78.9);
        insert into student values ('itcast_002','lisi',20,'nan',88.9);
        insert into student values ('itcast_003','wangwu',49,'nv',90.9);
        insert into student values ('itcast_004','zhaoliu',28,'nan',70.9);
        insert into student values ('itcast_005','huangjin',35,'nv',78.9);
        insert into student values ('itcast_006','linchi',19,'nan',68.8);
        insert into student (id,name,age,sex,score) values('itcast_009','hanCheng',35,'nan',90.1);

    Modify table data:
      

 update 表名 set 列名=值…… where 列名=值;
        update student name='zhangsan' where id='001';

    Delete table data:
      

 delete from student where id='001';
        delete from studnet where name='zhangsna';
        delete from student where name='lisi';

Four .DQL
    All information query:
        

select * from studnet;


    By column name query + range:
      

 select name,age,id from student from age>20;
        select name,age,id from student from age between 20 and 50;
        select name,age,id from student from age>20 and age<50;

    Fuzzy query:
    

    select *from student where name like '%xx%';


    To repeat the query:
     

   select distin sex from student;

    Action queries:
     

   select *, age=age+10 from student;

    Alias ​​the columns:
    

    select id ID,name NAME,age AGE,score SCORE from student;

    Sort query:
    

    select * from student order by age ASC;//升序
        select * from student order by age desc;//降序
        select * from student order by age desc,score asc;//先按年龄降序,年龄相同在按成绩升序


    Aggregate functions Query:
        COUNT (): the number of specified column is not a null rows;
        max (): maximum value of the specified column is calculated, if the specified string type column, then the order computation string;
        min (): calculated minimum specified column, if the specified column is of type string, the string using the order of operation;
        SUM (): calculated value and a specified column, if the specified type is not a numeric type, then the calculation result is 0;
        AVG (): calculating an average value refers to the column, if the column is not specified numeric type, then the calculation result is 0     

   select count(*) from student;//如果一条记录中,所有列全为null则不计数
        select count(*) from student where age>30;
        select count(id) ,count(name) from student;//列id中有null不计数,列name中有null不计数

        select sum(score) from student;
        select max(score) from studnet;
        select min(score) form student;
        select avg(score) from student;
        select count(name) as ZONGRENSHU,sum(score) as ZONGFENSHU from student;
        select sum(score+ifnull(age,0))from student;


    Query packet: (behind the current packet is a first select columns e.g. sex, the second must be a function of the polymerization)
    

    select sex,count(*) from student group by sex;
        select sex,count(*),max(score),min(score) from student group by sex;
        select sex,count(*) from student where score>80 group by sex;


        having statement:
      

     select sex,sum(score) from student group by sex having sum(score)>200;//查询总分大于200分的性别以及总分


            
            The number of queries for each department in wages and the number is greater than 15,000 greater than 2:
    

        select deptno,count(*) from emp where sal>15000 group by deptno having count(*)>2;


            Note: where is the grouping condition before, do not participate in packet
                  having grouped conditions are
     
    the order of execution and order of writing:
        the SELECT
        from
        the WHERE
        Group by
        having
        the Order by
        
    

    limit statement:
  

      select * from student limit 0,3;//查询三条记录从第0行开始
        select * from studnet limtt 3,4;//查询四条记录从第三行开始


        
    Backup / restore database:
        Export database script:
         

   mysqldump -u数据控用户名 -p数据库密码 要备份的数据库名 > 备份路径
            mysqldump -uroot -pxxxxx aaaa>D:/a.sql


            
        Execute database scripts:
        Option 1:
          

  mysql -u数据控用户名 -p数据库密码 要备份的数据库名 < 备份路径
            mysql -uroot -pxxxxx aaaa<D:/a.sql


        Option 2:
      

     source 之前备份好的数据库脚本文件
            source D:/a.sql


            For example: 1 first backup database file .sql file 2. Delete the configuration database in the creation of this database 3. Switch to the database to perform source D: /a.sql statement on the restoration of the database content
            
    integrity constraints - Primary key:
        Column Name column type (self increased to int) primary key [auto_increment],
    

    create table student(
            stu_id int primary key auto_increment,
            stu_name varchar(30)
        );


    Integrity constraints - foreign key:
        DNO int, / to the table columns that they have, in general, and the row of the table to be associated with the same
        // name of the foreign key constraint associated foreign key (associated with the row in this table) references the table table (the table associated with that column)
     

    create table student(
            stu_id int primary key auto_increment,
            stu_name varchar(30)
        );


        Note:
            1.constraint (constraint); References (reference);
            naming rules 2. Foreign key name is: fk_ This table name association table name _
            
    many relationship:
    For example:
     

   create table hasband(
            hid int primary key auto_increment,
            hname varchar(50)
        );
        
        create table table wife(
            wid int primary key auto_increment,
            wname varchar(50),
            hid int, -- 可以重复出现 
            constraint fk_wife_hasband foreign key(hid) references hasband(hid)
        );
        //利用本表的普通键作为外键引用外表主键,可以达到一对多的效果(多夫一妻)


        
    One relationship:
    foreign key features: non-null, unique, can be cited hid
    example:
     

   create table hasband(
            hid int primary key auto_increment,
            hname varchar(50)
        );
        
        create table table wife(
            wid int primary key auto_increment,
            wname varchar(50),
            constraint fk_wife_hasband foreign key(wid) references hasband(hid)
        );


        // use the primary key of this table as a foreign key, one can achieve the effect (monogamous)
        
    many relationship:
    For example:
      

  create table student(
            sid int primary key auto_increment,
            sname varchar(30)
        );
    
        create table teacher(
            tid int primary key auto_increment,
            tname varchar(30)
        );


        - Relationship association table (Table intermediate)
     

   create table stu_tea(
            sid int,
            tid int,
            constraint fk_student foreign key(sid) references student(sid),
            constraint fk_teacher foreign key(tid) references
            teacher(tid)
        );
        
        insert into student values(null,'zhangsan');
        insert into student values(null,'lisi');
        insert into student values(null,'wangwu');
        insert into student values(null,'zhaoliu');
        insert into student values(null,'hulil');
        
        insert into teacher values(null,'hahaha');
        insert into teacher values(null,'heihei');
        insert into teacher values(null,'hehehe');
        

 

     -- 加入关系表
        -- 1老师教过学生1、2、3、4
        insert into stu_tea values(1,1);
        insert into stu_tea values(2,1);
        insert into stu_tea values(3,1);
        insert into stu_tea values(4,1);
        -- 2老师教过2、4
        insert into stu_tea values(2,2);
        insert into stu_tea values(4,2);
        -- 3老师教过2、4、5
        insert into stu_tea values(2,3);
        insert into stu_tea values(4,3);
        insert into stu_tea values(5,3);
        -- 2、4学生被1、2、3老师都教过——多对多关系


        
    Multi-table queries:
    1. The combined result set
     ** requires two "result sets" the number of columns (two tables are not), the identical column type
      

create table ab (a int ,b varchar(20)) ;
create table cd (c int ,d varchar(20)) ;
select * from ab union all select * from ba;-- 不去重复行
select * from ab union select * from ba; -- 去重复行


        
    2. join query (query involving multiple tables, the first step is thought to use the primary foreign key Cartesian product)
     connected to the **
        ** dialect style: SELECT * FROM TABLE 1 1 alias, alias the WHERE Table 2 1 2 alias. xx = alias 2.xx   
            Example:

select e.ename,e.sal,d.dname
from emp e,dept d
where e.deptno=d.deptno;


        ** standard style: SELECT * FROM TABLE 1 INNER JOIN Table Alias 1 2 2 ON alias alias alias 1.xx = 2.xx
            Example:

select e.ename,e.sal,d.dname
from emp e inner join dept d
on e.deptno=d.deptno;


        (Comma dialect variable inner join, where variable ON)
        
     ** outer connecting
      the outer one is connected to a main left outer left table is based
      ** left outer: SELECT * FROM TABLE 1 alias 1 LEFT OUTER JOIN Table Alias 2 Alias 2 ON 1.xx = alias 2.xx
            Example:

select e.ename,e.sal,d.dname
from emp e left outer join dept d
on e.deptno=d.deptno;


            // emp table-based, then the main table, all the records whether conditions are not satisfied, are printed out when the conditions are not satisfied, the right table to print all use null to fill the seats
            
      

select e.name,e.sal,ifnull(d.dname,'无部门') as dname
from emp e left join dept d
on e.deptno=d.deptno; -- 人性化显示再起个别名


            
      Right outside **: SELECT * FROM TABLE 1 1 RIGHT OUTER JOIN Table Alias 2 Alias 2 ON alias 1.xx = alias 2.xx
            example:

select e.ename,e.sal,d.dname
from emp e right outer join dept d
on e.deptno=d.deptno;


            // dept table-based, then all records in the primary table does not meet the conditions regardless, are printed out when the conditions are not satisfied, left the table to print all use null to fill the seats
    
      ** Full connection: that is the outer left and the outer right-merge result set to OK
                can be used to complete the entire link UNION
                
    subquery: query has a query
        such as: (after where) to check the maximum wage people's information
         

select max(sal) from emp;-- 最高工资是多少
select * from emp where (select max(sal) from emp);


        (After from) the investigation department for the '30' people of information: for example,
         

select * from emp where deptno=30;-- 查询部门为30的人
select t.empno,t.name from (select * from emp where deptno=30) t;-- 给这个虚表起个名字


        1. When the positions:
            * a condition exists after WHERE
            * present as from the table (rows and columns)
        2. Conditions
            * (***) single separate: SELECT * FROM Table 1 column 1 the WHERE alias 1 [=,> !, <,> =, < =, =] (SELECT columns FROM table 2 alias the WHERE condition 2)
            * (**) single multiple lines: SELECT * FROM tABLE 1 alias the WHERE column 1 1 [IN, ALL, ANY] ( SELECT columns FROM table 2 alias 2 the WHERE condition)
            * (*) single-line multi-column: SELECT * FROM tABLE 1 alias 1 the WHERE (column 1, column 2) the IN (SELECT column 1, column 2 FROM tABLE 2 alias 2 the WHERE condition)
            * (***) rows and columns: SELECT * FROM tABLE 1 alias 1, (SELECT ....) alias 2 WHERE condition


    Example:
    1. found to have at least one employee of the department. Display department number, department name, department, location, number of sectors.
        Analysis:
            Column: d.deptno, d.dname, d.dloc, sector number
            table: dept d, emp e
            conditions: e.deptno = deptno (to Cartesian product)

select * from dept;//d.deptno,d.dname,d.dloc
select deptno,count(*) from emp group by deptno;//部门人数,作为子查询


        answer:

select d.*,z.cnt
from dept d inner join(select deptno,count(*) cnt from emp group by deptno) z 
on d.deptno=z.deptno;


    3. List the names of the names of all employees and their immediate superiors.
        Analysis:
            Column: employee name, the name of the upper
            table: emp e, emp m
            Condition: e.mgr = m.empno (employee number is equal to the higher number of employees is the direct supervisor relationship)

select * 
from emp e left outer join emp m 
on e.mgr=m.empno;//此时以null补位


        answer:

select e.ename,ifnull(m.ename,'BOSS') 
from emp e left outer join emp m
on e.mgr=m.empno;//此时以null补位


                
    4. List the hire date earlier than the direct superior of all employees of the number, name, department name.
        Analysis:
            Column: e.empno, e.ename, d.dname
            table: emp e, dept d, dept d
            condition: e.hiredate <m.hiredate
            
            First, do not check the department name, department number only check!
            Column: e.empno, e.ename, d.deptno
            table: emp e, dept d
            Condition: e.mgr = m.empno and e.hiredate <m.hiredate
            
        

select e.empno,e.ename,e.deptno,e.hiredate,m.ename,m.hiredate,d.deptno
from emp e,emp m
where e.mgr=m.empno and e.hiredate<m.hiredate
            


            Department number and then became the department name you need to use the dept table :( still have to remember to remove the Cartesian product)
            answer:
              

select e.empno,e.ename,d.deptno,e.hiredate,m.ename,m.hiredate,d.deptn
from emp e,emp m,dept d
where e.mgr=m.empno and e.hiredate<m.hiredate and d.deptno=e.deptno


            Conditions resolve:
                e.mgr = m.empno: the higher number of employees is equal to number of employees is the direct supervisor relationship
                e.hiredate <m.hiredate: entry earlier
                d.deptno = e.deptno: corresponding department name
            
    5. List name of the department and employee information in these sectors, while those who are not employees of the department are listed.
        Analysis:
            Column: *
            Table: emp e, dept d
            Condition: e.deptno = d.deptno
        Answer:
          

select * 
from emp e right outer join dept d
where e.deptno=d.deptno

    7. List the minimum salary is greater than 15,000 various kinds of work and the number of employees engaged in this work.
        Analysis:
            Column: job, count (*)
            Table: emp e
            Conditions: min (sal)> 15000
            packets: job
            
        Answer:
         

select job,count(*)
from emp e
group by job
having min(sal)>15000


    
    8. List the names of employees in the sales department, assuming sales department does not know the number.
        Analysis:
            Column: e.ename
            table: emo
            condition: e.deptno = (by dname check out deptno)
            
        answer:
          

select e.ename
from emp
whhere e.deptno=(select deptno from dept where dname='销售部');

    ***** four strap a subquery
    9. List salary higher than the company average salary of all employees information, where the name of the department, superiors, wage scales.
        (salgrade expressed registration form wage lists: wage levels (int), the minimum wage, maximum wage three)
        analysis:
            Column: *
            Table: emp e
            condition: sal> (check out the company's average wage)
        
            

select e.* ,d.dname,m.ename,s.grade
from emp e,dept d,emp m,salgrade s
where e.sal>(select avg(sal) from emp) and e.deptno=d.deptno and e.mgr=m.empno and e.sal between s.losal and s.hisal;


        Conditions:
            e.deptno = d.deptno: go Cartesian product, department
            e.mgr = m.empno: direct supervisor relationship
            e.sal between s.losal and s.hisal: salary grade
        answer:
          

select e.* ,d.dname,m.ename,s.grade
    from emp e left outer join dept d on  e.deptno=d.deptno
          left outer join emp m on e.mgr=m.empno
          left outer join salgrade s on e.sal between s.losal and s.hisal
where e.sal>(select avg(sal) from emp);


    
    10. List all employees and department name and Pang Tong doing the same work.
        Analysis:
            Column: emp *, dept.dname.
            Table: emp e, dept d
            condition: e.job = (check out the work Pang Tong name)
        
        answer :( Do not forget to Cartesian product)
            

select e.*,d.danme
from emp e,dept d
where e.deptno=d.deptno and job=(select job from emp where ename='庞统');


    *****
    13 years to detect, profits, annual increase over the
        answer:
            

select y1.*,ifnull(concat((y1.zz-y2.zz)/y2.zz*100,'%'),'0%') 增长比
from tb_year y1 left outer join tb_year y2
on y1.year=y2.year+1;
    


    


        

     

Guess you like

Origin blog.csdn.net/ym15229994318ym/article/details/100851550