MySQL基本操作

240 阅读2分钟

MySQL

一.常用命令

功能命令实例
查看mysql运行状态sudo systemctl status mysqldimage-20210121194408167
启动服务sudo systemctl start mysqld
关闭服务sudo systemctl stop mysqld

二.MySQL客户端工具

2.1 基于内置客户端操作

Mysql的账号和密码: root / ROOTroot_1

  • 登录

    mysql -u root -p
    
  • 查看数据库列表

     show databases; #3)查看数据库列表,注意命令结束使用 "分号"
    
  • 删除数据库

    drop database world; #4)删除数据库
    
  • 创建数据库

    create database world; #5)创建数据库
    
  • 使用该数据库

    use world; #6)使用该数据库
    
  • 查看数据表

    show tables; #7)查看当前数据(world)对应的数据表
    
  • 退出

    exit;
    

2.2基于第三方图形客户端操作

image-20210121203053889

三.初始化SQL脚本

  • 上传脚本文件world.sql-->/opt/data 【xftp】
  • 基于MySQL命令行客户端登录
  • 使用空数据库world
  • 在数据库world进行初始化脚本:使用命令source
[hadoop@hadoop01 ~]$ mysql -uroot -p #1)输入命令进入Mysql客户端
Enter password:

mysql> use world; #3)使用world

mysql> show tables; #4)没有引入前,没有数据表
Empty

mysql> source /opt/data/world.sql; #5)初始化脚本,要先用xftp上传
mysql> show tables; #6)说明初始化脚本成功

image-20210121211811797

四. MySQL常用操作

查看city表结构

desc 表名;

image-20210121212702282

检索country表涉及的洲

DISTINCT: 去重

select DISTINCT continent #select 后跟列名
from country #from 后跟表名
image-20210121212900736

检索city表

检索:城市编号id、城市名name、行政区district

#1)检索指定列
SELECT id,name,District
from city

#2)检索城市('New York','Kabul'SELECT id,name,District
from city
where name in('New York','kabul')#过滤

排序order by

题目:检索country表(国家名称、所在的洲continent) 按照continent降序、name升序排序

select Continent,name
from country
order by Continent desc,name asc

分组 group by

操作表: country表

统计各个洲的平均人口数量
select Continent, avg(Population) as avg_popu
from country
group by Continent
order by avg_popu desc
image-20210121213414801
统计各个洲的平均人口数量大于1W
select Continent, avg(Population) as avg_popu
from country
group by Continent
HAVING avg_popu > 10000 #筛选
order by avg_popu desc

image-20210121213457527

内连接(inner join)

题目:从city、country表

检索:(城市名称name、城市对应的地区district、城市所属国家名称[国家表的name])

select c1.name,c1.District,c2.name as countryName
FROM city as c1
join country as c2
on c1.CountryCode = c2.Code
image-20210121213732682