启动
- 按管理员模式打开命令命令提示符(黑色的),进入mysql/bin
cd D:
cd mysql/bin
- 输入密码,比如我的123123:
>mysql -u root -p
- 展示所有的数据库
>show databases;
>use hw
- 建立一个新的数据库
drop database if exists travel;
create database travel;
use travel;
show tables; 查看数据库中所有表格的名字
表上的操作
创建表
create table agent (
id int primary key,
name varchar(20)
);
- 添加限制条件,比如限制某一个是外键。mysql文档给出了一个外键demo。child表中foreign key元素一定要在parent表中可以查到。foreign key有三种
- cascade. parent表变化,child表也变化
- restrict. 不允许child表引用到的parent表中元素
- set null. if a row from the parent table is deleted or updated, the values of the foreign key column (or columns) in the child table are set to NULL.
constraint fk_demo foreign key (fkid) references fk_category(fkid) on update cascade on delete cascade;
- auto_increment. 自动+1. 如
create table agent
( id int auto_increment,
name varchar(100));
查看表
select * from agent;–选择表中所有内容
describe agent;–查看类型描述
表中插入数据
- 插入单条数据
insert into agent(id,name) values (1,‘df’);
- 使用select批量插入
insert into new_york_agent (select * from agents where city=‘New York’);
表上的查询操作
- select进行简单选择查询。order by 还可以按照多个属性来排序。limit 如果不配合order 来使用,每次得到的结果可能不同。
select pid from products where price!=1.5 and city=‘Dallas’ order by name desc limit 4;
- cross product 笛卡尔积的使用。A product B指A和B所有可能的拼接。
select o.aid,a.aname from orders o,agents a where o.aid=a.aid;
- join 连接的使用. 根据on后面的条件进行连接。
select o.aid,a.aname from orders o,agents a where o.aid=a.aid;
注意left join和join的区别:left join保证Join出来数量不变,其中可能右边全是Null,但是join只会选择右边不全是Null的情况。
- 聚合函数使用,常用的数学函数如avg, max, min, sqrt, 等等。select中可以有多个聚合函数,除了聚合函数的column,如果不配上group by会导致UB。聚合函数只能出现在select子句中,select子句中可能有多个聚合函数。
select avg(dols) as AVG_DOL from orders ;
- group by分类
select pid, avg(dols) as AVG_DOL from orders group by pid;
- having子句进行过滤,筛选出符合having子句的结果。
select pid,avg(o.dols) as AVG_DOL from orders o join customers c on o.cid=c.cid where c.city=‘Dallas’ group by pid order by AVG_DOL;
- exists 存在性
select cid from customers where exists( select * from orders o where customers.cid=o.cid and o.aid=‘a01’);
- in
select aid from agents a where a.city in (select city from customers where perc>4);
- row_number(). 给每一行加上一个标号。类似于一种聚合函数,是最后做的,所以在进行分层采样的时候需要嵌套查询。
select * from (select *, ROW_NUMBER() OVER(PARTITION BY aid) as number from orders) tmp where number<=2 ;
- like 配合正则表达式使用
select * from agents where city like ‘D%’;
- offset配合Limit,获取第K大的元素
select
ifnull(
(select Salary from Employee order by Salary desc limit 1 offset 1),
null
) as SecondHighestSalary;
- isnull(query, null). 如果是Null填入第二个参数的默认值。
退出
exit