暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

第四章 SQL基本应用

蜜蜂点滴 2020-05-27
310

1、distinct 去重复

select DISTINCT(cno) from sc;

效率比较低,版本8.0变化了。

2、别名

列别名:

表别名:

select a.sname as '学生姓名',b.score as '成绩'

from student as a

JOIN sc as b

on a.sno=b.sno

where b.score<80;

3、外连接

left join;

最左原则;

select a.name,b.name,b.surfacearea

left from city as a

join country as b

on a.countrycode=b.code

where a.population<100;

左侧表都显示。

4、information_schema

虚拟库;

在路径下没有information_schema;

元数据:基表,无法直接查询和修改的

DDL进行元数据修改;

show语句进行查看,information_schema;

查看表结构:desc information_schema.TABLES

 TABLE_SCHEMA 表所在的库;

TABLE_NAME   表名;

TABLE_TYPE 表;

ENGINE表的存储引擎;

TABLE_ROWS表的行数;

 AVG_ROW_LENGTH 平均行长度;

INDEX_LENGTH 索引的长度;

-- 要查询整个数据库中所有的库对应的表名

select TABLE_SCHEMA,TABLE_NAME from information_schema.TABLES

-- 查询school库下的所有表名

select TABLE_SCHEMA,table_name FROM information_schema.TABLES where TABLE_SCHEMA='school'

-- 查询整个数据库中所有的库对应的表名,每个库显示成一行

select TABLE_SCHEMA,GROUP_CONCAT(table_name) FROM information_schema.TABLES GROUP BY TABLE_SCHEMA;

-- 统计一下每个库的真实数据量

-- 没张表的数据量(占用多大空间)AVG_ROW_LENGTH*TABLE_ROWS+INDEX_LENGTH

select sum(AVG_ROW_LENGTH*TABLE_ROWS+INDEX_LENGTH)/1024/1024 as '大小' FROM information_schema.TABLES

-- 拼接concat

select concat(user,"@",host) from mysql.user

-- 生产需求 备份

mysqldump -uroot -p123456 world_area city >/tmp/world_city.sql

-- 模仿以上命令,对整个数据库下的1000张表进行单独备份,排除sys,performance_schema,information_schema

select concat("mysqldump -uroot -p ",table_schema," ",table_name," >/tmp/",table_schema,"_",table_name,".sql")

from information_schema.tables

where table_schema not in('sys','performance_schema','information_schema')

into OUTFILE '/tmp/bak.sh'

-- 报错:> 1290 - The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

-- secure-file-priv 在my.cnf里设置安全路径,添加上secure-file-priv=/tmp

-- 模仿以下语句,批量实现world下所有表的操作语句生成

alter table world_area.city discard TABLESPACE;

--查看所有的表:

select table_name,table_schema from information_schema.tables;

5、show语句

-- 查看数据库

show databases

--查看数据库表

show tables;

show tables from world_area

-- 查看建表语句

show create table;

-- 查看建库语句

show create database

-- 查看指定数据库下的表名

show tables from world_area

-- 查看用户权限信息

show grants for root@'localhost'

-- 查看所有的字符集

show charset;

-- 查看校对规则

show collation

-- 查看链接情况

show full processlist

-- 查看数据库的整体状态

show status

show status like '%lock%'

-- 查看数据库所有变量情况

show variables

-- 查看所有支持的存储引擎

show engines

-- 查看所有innodb存储引擎状态情况

show engine innodb status;

-- 查看二进制情况

show binary logs

-- 查看二进制日志事件

show binlog events in

-- 查看relay日志事件

show relaylog events in

-- 查看从库状态

show slave status

-- 查看数据库binlog位置信息

show master status


文章转载自蜜蜂点滴,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论