mysql入门使用Tip

启动

  1. 按管理员模式打开命令命令提示符(黑色的),进入mysql/bin
cd D:
cd mysql/bin
  1. 输入密码,比如我的123123:
>mysql -u root -p


  1. 展示所有的数据库
>show databases;
>use hw
  1. 建立一个新的数据库

drop database if exists travel;
create database travel;
use travel;
show tables; 查看数据库中所有表格的名字

表上的操作

创建表

create table agent (
id int primary key,
name varchar(20)
);

  1. 添加限制条件,比如限制某一个是外键。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;

  1. auto_increment. 自动+1. 如

create table agent
( id int auto_increment,
name varchar(100));

查看表

select * from agent;–选择表中所有内容
describe agent;–查看类型描述

表中插入数据

  1. 插入单条数据

insert into agent(id,name) values (1,‘df’);

  1. 使用select批量插入

insert into new_york_agent (select * from agents where city=‘New York’);

表上的查询操作

  1. select进行简单选择查询。order by 还可以按照多个属性来排序。limit 如果不配合order 来使用,每次得到的结果可能不同。

select pid from products where price!=1.5 and city=‘Dallas’ order by name desc limit 4;

  1. cross product 笛卡尔积的使用。A product B指A和B所有可能的拼接。

select o.aid,a.aname from orders o,agents a where o.aid=a.aid;

  1. 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的情况。

  1. 聚合函数使用,常用的数学函数如avg, max, min, sqrt, 等等。select中可以有多个聚合函数,除了聚合函数的column,如果不配上group by会导致UB。聚合函数只能出现在select子句中,select子句中可能有多个聚合函数。

select avg(dols) as AVG_DOL from orders ;

  1. group by分类

select pid, avg(dols) as AVG_DOL from orders group by pid;

  1. 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;

  1. exists 存在性

select cid from customers where exists( select * from orders o where customers.cid=o.cid and o.aid=‘a01’);

  1. in

select aid from agents a where a.city in (select city from customers where perc>4);

  1. row_number(). 给每一行加上一个标号。类似于一种聚合函数,是最后做的,所以在进行分层采样的时候需要嵌套查询。

select * from (select *, ROW_NUMBER() OVER(PARTITION BY aid) as number from orders) tmp where number<=2 ;

  1. like 配合正则表达式使用

select * from agents where city like ‘D%’;

  1. offset配合Limit,获取第K大的元素

select
ifnull(
(select Salary from Employee order by Salary desc limit 1 offset 1),
null
) as SecondHighestSalary;

  1. isnull(query, null). 如果是Null填入第二个参数的默认值。

退出

exit

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值