• sql语句的基本操作


    建立一个数据库

    create DATABASE mydatabase;

    建立一张数据表:

    ##创建一个员工表##
    create
    table employee( eid int not NULL PRIMARY KEY auto_increment, ##id## ename varchar(20) not null unique, ##name## salary int, ##工资## deptid int ##部门号## );

    批量插入一些数据:

    INSERT into employee(ename,salary,deptid)
    VALUES('小孔',4562,5),
    ('小列',3457,2),
    ('小课',3457,1),
    ('小白',4566,3),
    ('小系',3468,2),
    ('小个',9345,3);

     

    查询数据:

    1、根据部门号从高到低,工资从低到高列出每个员工的信息

    SELECT * from employee ORDER BY deptid DESC,salary;

    2、列出各个部门中工资高于本部门的平均工资的员工数和部门号,并按部门号排序

    SELECT em.deptid as '部门号',count(*) as '员工数' from employee em WHERE salary > 
    (SELECT AVG(salary) FROM employee WHERE deptid = em.deptid ) GROUP BY em.deptid;

    3、查询姓名不为空的所有数据

    select * from employee where ename is not null;

    4、查询所有的部门号,不重复

    select DISTINCT deptid from employee;

    5、查询从2开始5条数据

    ##limit 一般用于对数据的分页,用法:limit a,b 。a 指的是数组下标从0开始,b指的是显示b条记录##
    select
    * from employee LIMIT 1,5;

    6、查询姓名为“小”开头的数据

    select * from employee where ename like '小%';

    查询姓名中不包含“心”的数据

    SELECT * from employee WHERE ename not like '%心%';

    匹配的通配符

    通配符 描述
    % 替代一个或多个字符
    _(注:下划线) 仅替代一个字符
    [charset] 字符列中的任何单一字符
    [^charset]或[!charset] 不在字符列中的任何单一字符

    删除数据:

    删除部门号为5的数据

    DELETE FROM employee where deptid = 5;

    更新数据:

    将小心调用部门6

    update employee set deptid = 6 where ename = '小心'; 

    添加一列地址

    ALTER table employee add addr varchar(255);

    将地址列的列名改为address,并改变其类型

    ALTER table employee CHANGE  addr address varchar(512); 

    将地址列删除掉

    ALTER table employee drop column  addr;

    给id添加主键

    ALTER TABLE employee add constraint employeeId PRIMARY KEY (eid);

    给名字添加唯一约束

    alter table employee add constraint onlyone UNIQUE(ename);

    添加表中addr的默认值

    alter table employee ALTER addr set default 'XXX' ;

    给部门表添加外键(加外键一定必须是另一表中的主键,并且两个属性必须完全相同)

    alter table employee add constraint fk_dept FOREIGN KEY (deptid) references dept(id); 

    给部门id加值范围的约束>0

    alter table employee add constraint checkid check(id > 0);

    在表中创建索引

    Create Index PersonIndex on person (lastName)

    索引不止一个列

    create index personIndex on person(lastName,firstName)

    删除名字上的索引onlyone

    drop index onlyone on employee;

    删除表

    drop table employee;

    删除数据库

    drop database test

    不删除表只是清除其中的数据

    truncate table employee
  • 相关阅读:
    【Flink系列十二】使用OpenResty 在InfluxDB协议层拦截Flink指标
    【Azkaban优化】防止IP变化导致频繁登录
    困扰多年的Quartz重复调度的问题,终于找到原因
    【Flink系列十一】FlinkSQL Gateway以及支持Kerberos多租户的实现思路
    【Flink系列十三】FlinkKafkaConnector KafkaSource FlinkKafkaConsumer没有上报指标
    IDEA项目结构出现 0% methods,0% lines covered up
    java去重 up
    svndown下来项目但是导入不了maven包,解决办法 up
    新型病毒加强勒索病毒预防 up
    java list 时间排序, up
  • 原文地址:https://www.cnblogs.com/sker/p/5761835.html
Copyright © 2020-2023  润新知