Mysql增删改查、Mysql查询属性、Mysql使用案例

create database

创建db1数据库

create database db1 charset utf8;

show databases

查看数据库

show databases;

alter database

修改库的编码

alter database db1 charset gdk;

drop database

删除db1数据库

drop database db1;

use databases

使用数据库

use database;

show tabels

查看数据表

show tabels;

select ... where

在stu表中查询sid为1的所有数据

select * from stu where sid =1;

create table

创建一个数据表stu 字段有id(唯一key自增)name字符16个,age不能为空

create table stu(id int primary key auto_increment,name char(16),age int no null);

inset into

在表格插入名字123,年龄10

inset into stu(name,age) value("123",10);

alter table stu rename

修改表格名

alter table stu rename stu_new;

alter table stu modify

修改stu的age字段类型

alter table stu modify age char(4) not null;  

alter table stu add

新增一个字段名

alter table stu add sex enum("男","女");

alter table stu drop

删除一个字段名

alter table stu drop sex;

alter table stu change

修改原有字段名

alter table stu change name  name_new char(16);

desc tabelname

查看数据表的字段属性

desc tabelname;

updata stu set

更新stu表格的age当id为2的数据

updata stu set age=xx  where id=2;

delete from ... where ..

清除表格数据当id为2

delete from stu where id=2;

查询属性

select distinct 字段1,字段2 from 表名
        where 条件
        group by field
        having 筛选条件
        order by filed
        limit 条数
        distinct去重

注:

group by field 根据什么进行分组,一般是某个字段或多个字段
order by field 根据什么进行排序,一般是某个字段或多个字段
having主要配合group by 使用,对分组后的数据进行过滤,里面可以使用 聚合函数
where是针对select查询的过滤,各有区别和用处
优先级:
from
where
group by
select
distinct
having
order by
limit

 

案例:

1、查询姓名末尾的字符

select emp_name,substring(reverse(emp_name),1,1) as new_name from emp;
select emp_name,substring(emp_name,-1) as new_name from emp;

2、查询以“张”开头的三个字员工信息

select * from emp where emp_name like "张__";

3、查询以"z"开头的员工信息

select * from emp where emp_name like "z%";

4、计算每个部门有多少人?大于6个人的部门有哪些?

select post,count(emp_name) 人数 from emp group by post;
select post,count(emp_name) 人数 from emp group by post having count(emp_name)>6;

5、计算每个部门的平均工资从高到低排序(order by desc or asc)

select post,AVG(salary) as avg_salay from emp group by post;
select post,AVG(salary) as avg_salay from emp group by post order by desc;

6、查询成绩第一的

select max(num) from stu;
select * from stu where num = (select max(num) from stu);

7、排除成绩第一的取第二成绩的

select max(num) from stu where num<(select max(num) from stu);
select * from stu where num = (select max(num) from stu where num<(select max(num) from stu));

8、合并第一和第二的数据

select * from stu where num = (select max(num) from stu)
unsion all
select * from stu where num = (select max(num) from stu where num<(select max(num) from stu));

 

你可能感兴趣的:(Mysql,mysql,数据库,sqlserver)