1、初始MySQL
-
JavaEE:企業級java開發 Java Web
-
前端:(頁面:展示數據)
-
後臺:(連接點:數據庫JDBC,鏈接前端(控制,控制視圖跳轉,和給前端傳送數據))
-
數據庫:(存數據,TXT,Excel,word)
只會寫代碼,學好數據庫,基本混飯喫!
操作系統,數據結構預算法!當一個不錯的程序員
離散數學,數字電路,體系結構,編譯原理+實戰經驗,高級程序員::優秀的程序員
1.1、爲什麼學數據庫
-
崗位需求
-
現在的世界,大數據時代,得數據者得天下
-
被迫需求,存數據
-
數據庫是所有軟件體系中最核心的存在 DBA
1.2、什麼是數據庫
- 數據庫:(DB Database)
- 概念:數據倉庫,軟件,安裝在操作系統上(window,Linux,mac。。。。),之上!可存儲大量的數據,500萬
- 作用:存儲數據,管理數據
1.3、數據庫分類
關係型數據庫:(SQL)
- MySQL,Oracle,SQL Server,DB2,SQLlite
- 通過表和表之間,行和列之間的關係進行數據的存儲,學員信息表,考勤表,…
非關係型數據庫:(No SQL)Not Only
- Redis,MongoDB
- 非關係型數據庫,對象存儲,通過對像的自身的屬性來決定。
DBMS(數據庫管理系統)
- 數據庫的管理軟件,科學有效的管理我們的數據,維護和獲取數據。
- MySQL:數據庫管理系統
1.4、MySQL簡介
MySQL是一個關係型數據庫管理系統
前世:瑞典MySQL AB公司
今生:屬於Oracle旗下產品
MySQL是最好的RDBMS(Relational Database Management System , 關係數據庫管理系統)應用軟件之一。
開源的數據庫軟件~
體積小,速度快,總體擁有成本低,招人成本比較低,所有人必須會
中小型網站,或者大型網站,集羣!
官網:https://www.mysql.com
安裝建議:
- 儘量不要使用exe安裝,卸載太費勁了。
- 儘可能使用壓縮包安裝
- 網盤裏有壓縮包資源:5.7.29和5.7.19 5.7版本穩定,有計算列之類的東西
1.5、安裝MySQL
教程: https://www.cnblogs.com/hellokuangshen/p/10242958.html
1、解壓
2、把這個包放到電腦環境目錄下
3、配置環境變量
4、新建mysql配置文件my.ini
[mysqld]
basedir=D:\Program Files\MySQL-5.7.29\
datadir=D:\ProgramData\MySQL\Data-5.7\data\
port=3306
skip-grant-tables
5、啓動管理員模式下的CMD, 並將路徑切換至mysql下的bin目錄 ,運行所有以下命令
6、安裝mysql服務 mysqld –install
7、初始化數據庫文件 mysqld --initialize-insecure --user=mysql
8、啓動mysql進去修改密碼
update mysql.user set authentication_string=password('123456')
where user='root' and Host = 'localhost';
# 刷新權限
flush privileges;
9、用命令行進入MySQL mysql –u root –p
進入mysql管理界面(密碼可爲空)
10、住掉ini中跳過密碼的語句
11、重啓mysql。連接測試,如果連接成功就完成了。
1.6、連接數據庫
命令行連接
mysql -u root -p --連接數據庫
update mysql.user set authentication_string=password('123456') where user='root' and HSOT = 'localhost'; -- 修改用戶密碼
flush privileges; --刷新權限
-----------------------------------------
--所有語句都使用;結尾
show databases; --查看所有數據庫
use school; --切換數據庫
-- 顯示:Database Changed
show tables; --顯示數據庫中所有的表
describe student; --顯示數據庫中所有表的信息
create database test; --創建一個數據庫
exit; --退出連接
-- 單行註釋(SQL本來的註釋)
/* (SQL多行註釋)
helloi
asdafqw
*/
數據庫xxx語言
- DDL:數據庫定義語言
- 創建,刪除,更改表結構
- DML:數據庫操作語言
- 插入,刪除,更改數據
- DQL:數據庫查詢語言
- 查詢數據
- DCL:數據庫控制語言
- 用來設置或更改數據庫用戶或角色權限
- TCL:事務控制語言
- 用來提交和回滾事務
2、操作數據庫
操作數據庫>操做數據庫中的表>操作數據庫中表的數據
mysql關鍵字不區分大小寫
2.1、操作數據庫
1、創建數據庫
create database [if not exists] wostes; -- []代表可選的參數 {}代表必選的參數
2、刪除數據庫
drop database [if exists] wostes;
3、使用數據庫
use `school`;
4、查看數據庫
show databases; --查看所有數據庫
2.2、數據庫的列類型
數值
類型 | 說明 | 大小 |
---|---|---|
tinyint | 十分小的數據 | 1個字節 |
smallint | 較小的數據 | 2個字節 |
mediumint | 中等大小的數據 | 3個字節 |
int | 標準的整數 | 4個字節(常用) |
bigint | 較大的數據 | 8個字節 |
float | 浮點數 | 4個字節 |
double | 浮點數 | 8個字節 |
decimal | 字符串形式的浮點數:金融計算時,一般使用decimal | 基本沒有限制,解決Java的精度問題 |
字符串
類型 | 說明 | 大小 |
---|---|---|
char | 字符串固定大小的 | 0-255 |
varchar | 可變字符串 | 0-65535(常用) |
tinytext | 微型文本 | 28 -1 |
text | 文本串(保存大文本) | 216-1 |
時間日期
java.util.Date
類型 | 說明 |
---|---|
date | YYYY-MM-DD 日期格式 |
time | HH:mm:ss 時間格式 |
datetime | YYYY-MM-DD HH:mm:ss 最常用的時間格式 |
timestamp | 時間戳,1970.1.1到現在的毫秒數 也較爲常用 |
year | 年份表示 |
null
- 沒有值,未知
- 注意:不要使用NULL參與計算,結果爲NULL
2.3、數據庫的字段屬性(重點)
Unsigned:
- 無符號的整數
- 聲明瞭該列不能聲明爲負數
zerofill:
- 0填充
- 不充足的位數使用0來填充, int(3) — 5 ----> 005
自增:
- 通常理解爲自增,自動在 上一條記錄 的基礎上+1(默認)
- 通常用來設計唯一的主鍵~ index ,必須是整數類型
- 可以定義設計主鍵自增的起始值和步長
非空 NULL not null
- 假設設置爲 not null ,如果不給它賦值,就會報錯!
- NULL,如果不填寫值默認就是null
默認:
- 設置爲默認值
- sex,默認值爲 男 ,如果不指定該列的值,則會有默認的值!
/* 每一個表,都必須存在以下五個字段!阿里規範,做項目時使用
id 主鍵
`version` 樂觀鎖
is_delete 僞刪除
gmt_create 創建時間
gmt_update 修改時間(最後更新時間)
*/
2.4、創建數據庫表(重點)
-- 目標:創建一個school數據庫
-- 創建學生表(列,字段)使用sQL創建
-- 學號int 登錄密碼varchar(20)姓名,性別varchar(2),出生日期(datatime),家庭住址,emai1
-- 注意點,使用英文(),表的名稱和字段儘量使用``括起來
-- AUTO_INCREMENT 自增
-- 字符串使用單引號括起來!
-- 所有的語句後面加',',最後一個不用加
-- PRIMARY KEY 主鍵,一般一個表只有唯一一個主鍵
create table if not exists `student`(
`id` int(4) not null auto_increment comment '學號',
`name` varchar(30) not null default '匿名' comment '姓名',
`pwd` varchar(20) not null default '123456' comment '密碼' ,
`sex` varchar(2) not null default '女' comment '性別',
`birthday` datetime default null comment '出生日期',
`address` varchar(100) default null comment '家庭住址',
`email` varchar(50) default null comment '郵箱',
primary key (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
格式:
create table [if not exists] `表名`(
`字段名` 列類型 [屬性] [索引] [註釋],
`字段名` 列類型 [屬性] [索引] [註釋],
...
`字段名` 列類型 [屬性] [索引] [註釋]
)[表類型] [字符集設置] [註釋]
獲取一些信息:
show create database test; -- 查看創建數據庫的語句
show create table student; -- 查看student數據表的定義語句
desc student; -- 顯示錶的結構
2.5、數據表的類型
-- 關於數據庫的類型
/*
INNODB 默認使用~
MyISAM 早些年使用
*/
MYISAM | INNODB | |
---|---|---|
事務支持 | 不支持 | 支持 |
數據行鎖定 | 不支持(鎖住整個表) | 支持 |
外鍵約束 | 不支持 | 支持 |
全文索引 | 支持 | 不支持 |
表空間大小 | 較小 | 較大,約爲MyISAM的兩倍 |
常規使用操作:
- MYISAM:節約空間,速度較快
- INNODB:安全性高,事務的處理,多表多用戶操作
在物理空間存在的位置
- 所有的數據庫文件都存貯在data目錄下,一個文件夾就對應一個數據庫;
- 本質還是文件存儲!
MySQL 引擎在物理文件上的區別:
- INNODB 在數據庫表中只有一個*.frm文件,以及上級目錄下的
ibdata1
文件 - MYISAM 對應文件:
- *.frm 表結構的定義文件
- *.MYD 數據文件(data)
- *.MYI 索引文件(index)
設置數據庫表的字符集編碼
CHARSET=utf8
-
不設置的話,會是MySQL默認的編碼集(不支持中文)
-
MySQL的默認編碼是Latin1,不支持中文
-
在my.ini中配置默認的編碼
character-set-server=utf8
2.6、修改表刪除表
修改
-- 修改表名 : alter table 舊錶名 rename as 新表名;
alter table `teacher` rename as `teacher1`;
-- 增加表的字段:alter table `表名` add 字段名 列屬性;
alter table `teacher1` add age int(11);
-- 修改表的字段:(重命名,修改約束)
-- alter table `表名` modify 字段名 列屬性;
alter table `teacher1` modify `age` varchar(11); -- 修改約束
-- alter table `teacher1` change `舊名字` `新名字` [列屬性];
alter table `teacher1` change `age` `age1` int(1); -- 字段重命名
-- 刪除表的字段:alter table `表名` drop `字段名`;
alter table `teacher1` drop `ag1e`;
刪除
-- 刪除表(如果表存在在刪除)
drop table if exists `teacher1`;
所有的創建和刪除操作儘量加上判斷,以免報錯~
注意點:
- `` 字段名,使用這個包裹
- 註釋:-- 和 /* */
- SQL關鍵字大小寫不敏感,建議寫小寫
- 所有符號全部用英文(半角)
3、數據庫管理
3.1、外鍵(瞭解即可)
方式一:在創建表時,增加約束(麻煩,比較複雜)
create table if not exists `grade`(
`gradeid` int(10) not null auto_increment comment '年級ID',
`gradename` varchar(20) not null comment '年級名稱',
primary key (`gradeid`)
)engine=innodb default CHARSET=utf8;
-- 學生表的gradeid字段 要去引用年級表的gradeid
-- 步驟:
-- 定義外鍵key
-- 給這個外鍵添加約束(執行引用) references 引用
create table if not exists `student`(
`id` int(4) not null auto_increment comment '學號',
`name` varchar(30) not null default '匿名' comment '姓名',
`pwd` varchar(20) not null default '123456' comment '密碼' ,
`sex` varchar(2) not null default '女' comment '性別',
`birthday` datetime default null comment '出生日期',
`gradeid` int(10) not null comment '學生的年級',
`address` varchar(100) default null comment '家庭住址',
`email` varchar(50) default null comment '郵箱',
primary key (`id`),
key `FK_gradeid` (`gradeid`) ,
constraint `FK_gradeid` foreign key (`gradeid`) references `grade`(`gradeid`)
)engine=Innodb default charset=utf8;
- 刪除有外鍵關係的表的時候,必須要先刪除引用別人表的表(從表),再刪除被引用的表;
- 例如:想刪除grade表時必須先刪除student表
方式二:在創建表時沒有外鍵關係
create table if not exists `student`(
`id` int(4) not null auto_increment comment '學號',
`name` varchar(30) not null default '匿名' comment '姓名',
`pwd` varchar(20) not null default '123456' comment '密碼' ,
`sex` varchar(2) not null default '女' comment '性別',
`birthday` datetime default null comment '出生日期',
`gradeid` int(10) not null comment '學生的年級',
`address` varchar(100) default null comment '家庭住址',
`email` varchar(50) default null comment '郵箱',
primary key (`id`)
)engine=innodb default charset=utf8;
-- 在創建表時沒有外鍵關係
alter table `student`
add constraint `FX_gradeid` foreign key (`gradeid`) references `grade`(`gradeid`);
-- ALTER TABLE 表 ADD CONSTRAINT 約束名 FOREIGN KEY(作爲外鍵的列) REFERENCES 哪個表(哪個字段)
以上的操作都是物理外鍵,數據庫級別的外鍵,我們不建議使用,(避免數據庫過多造成困擾,瞭解即可)
最佳實踐
- 數據庫就是單純的表,只用來存數據,只有行(數據)和列(字段)
- 我們想使用多張表的數據,想使用外鍵:程序去實現
3.2、DML語言(全部記住)
數據庫意義: 數據存儲,數據管理
DML語言:數據操縱語言
- insert
- update
- delete
3.3、添加
insert
-- 插入語句(添加)
-- insert into 表名(字段名,字段名,...) values (值1),(值2),(值3),...
insert into `grade`(`gradename`) values ('大四');
-- 由於主鍵自增我們可以省略,(如果不寫表的字段,他會一一匹配)
insert into `grade` values ('大三'); -- 因爲一一對應,所以報錯
-- 改正
insert into `grade` values (2,'大三');
-- 一般寫插入語句,我們一定要數據和字段一一對應
-- 插入多個字段
insert into `grade`(`gradename`)
values ('大二'),('大一');
insert into `student`(`name`) values ('張三');
insert into `student`(`name`,`pwd`,`sex`) values ('小明','愛大愛','男');
insert into `student`(`name`,`pwd`,`sex`)
values ('小明1','asdas','男'),('小dong','asdadas','女');
語法:insert into 表名(字段名,字段名,...) values (值1),(值2),(值3),...
注意事項:
- 字段和字段之間用英文 逗號隔開
- 字段是可以省略的,但是後面的值必須一一對應,不能少
- 可以同時插入多條數據,values後面的值,需要使用,隔開即可
values (值1),(值2),(值3),...
3.4、修改
update 修改誰(條件) set 字段名 = 新值
-- 修改學生名字
update `student` set `name`='kuangshen' where id=1;
-- 不指定條件的情況下,會改動所有表
update `student` set `name`='小明';
-- 修改多個屬性 逗號隔開
update `student` set `name`='xixix',`sex`='男' where id=1;
-- 語法
-- update `表名` set colunm_name=value,[colunm_name=value,...] where 條件;
條件: where 子句 運算符 id等於某個值,大於某個值,在某個區間內修改
操作符會返回 布爾值
操作符 | 含義 | 範圍 | 結果 |
---|---|---|---|
= | 等於 | id=5 | |
<> 或 != | 不等於 | id<>6 | |
> | 大於 | id>6 | |
< | 小於 | id<6 | |
<= | 小於等於 | id<=6 | |
>= | 大於等於 | id>=5 | |
between … and … | 在範圍之間(閉區間) | [1,4] | |
and | A和B && | 5>1 and 3>1 | true |
or | A或B || | 5>1 or 3<1 | true |
-- 通過多個條件來定位數據
update `student` set `sex`='x' where `name`='小明' and `sex`='女';
語法:update 表名 set colunm_name=value,[colunm_name=value,...] where 條件;
注意:
- column_name 是數據的列,儘量帶上``
- 條件,篩選的條件,如果沒有指定,則會修改所有的列
- value是一個具體的值,也可以是一個變量
update `student` set `birthday`=current_time where `name`='小明' and `pwd`='asdas';
3.5、刪除
delete 命令
語法:delete from 表名 [where 條件]
-- 刪除數據(避免這樣寫,會全部刪除)
delete from `student`;
-- 刪除指定數據
delete from `student` where id=1;
truncate 命令
作用:完全清空一個數據表,表的結構和索引約束不會變!
delete 和 truncate 的區別
- 相同點:都能刪除數據,,都不會刪除表結構
- 不同點:
- truncate 重新設置
自增列
計數器會歸零 - truncate 不會影響事務
- truncate 重新設置
-- 測試 delete 和 truncate 的不同
create table `test` (
`id` int not null auto_increment,
`coll` varchar(20) not null,
primary key(`id`)
)engine=Innodb default charset=utf8;
insert into `test` (`coll`) values('das');
delete from `test` ; -- 不會影響自增
truncate table `test`; -- 自增重新從1開始計算
瞭解即可:DELETE刪除的問題
,重啓數據庫,現象
- INNODB :自增列會從1開始,(自增列的計數存在內存中,斷電即失)
- MYISAM :繼續從上一個自增量開始(存在文件中,不會丟失)
4、DQL查詢數據(最重點)
4.1、DQL
(Data Query LANGUAGE :數據查詢語言)
- 所有的查詢操作都用它
select
- 簡單的查詢,複雜的查詢都能做
- 數據庫中最核心的語言,最重要的語句
- 使用頻率最高的語句
Select常用語法:
SELECT [ALL | DISTINCT]
{* | table.* | [table.field1[as alias1][,table.field2[as alias2]][,...]]}
FROM table_name [as table_alias]
[left | right | inner join table_name2] #聯合查詢
[WHERE ...] -- 指定結果需滿足的條件
[GROUP BY ...] -- 指定結果按照哪幾個字段來分組
[HAVING] -- 過濾分組的記錄必須滿足的次要條件
[ORDER BY ...] -- 指定查詢記錄按一個或多個條件排序
[LIMIT {[offset,]row_count | row_countOFFSET offset}];
-- 指定查詢的記錄從哪條至哪條
==注意:[]
代表可選,{}
代表必選
Select 完整的語法:
SELECT
[ ALL | DISTINCT | DISTINCTROW ]
[ HIGH_PRIORITY ]
[ STRAIGHT_J0IN ]
[ SQL_SMALL_RESULT ] [ SQL_BIG_RESULT] [ SQL_BUFFER_RESULT]
[ SQL_CACHE | SQL_NO_CACHE] [ SQL_CALC_FOUND_ROWS]
select_expr [, select_expr...]
[ FRoM table_references
[ PARTITION partition_list]
[ WHERE where_condition ]
[ GROUP BY { col_name | expr | position}
[ ASC | DESC],...[ WITH ROLLUP]]
[ HAVING where_condition]
[ ORDER BY { col_name | expr | position}
[ ASC | DESC ],..]
[ LIMIT { [offset,] row_count | row_count OFFSET offset}]
[ PROCEDURE procedure_name(argument_1ist)]
[INTO OUTFILE 'file_name'
[CHARACTER SET charset_name]
export_options
| INTO DUMPFILE 'file_name'
| INTO var_name [,var_name]]
[FOR UPDATE | LOCK IN SHARE MODE]]
4.2、測試素材
/*
SQLyog Ultimate v10.00 Beta1
MySQL - 5.7.19 : Database - school
*********************************************************************
*/
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`school` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `school`;
/*Table structure for table `grade` */
DROP TABLE IF EXISTS `grade`;
CREATE TABLE `grade` (
`GradeID` INT(11) NOT NULL AUTO_INCREMENT COMMENT '年級編號',
`GradeName` VARCHAR(50) NOT NULL COMMENT '年級名稱',
PRIMARY KEY (`GradeID`)
) ENGINE=INNODB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*Data for the table `grade` */
INSERT INTO `grade`(`GradeID`,`GradeName`) VALUES (1,'大一'),(2,'大二'),(3,'大三'),(4,'大四'),(5,'預科班');
/*Table structure for table `result` */
DROP TABLE IF EXISTS `result`;
CREATE TABLE `result` (
`StudentNo` INT(4) NOT NULL COMMENT '學號',
`SubjectNo` INT(4) NOT NULL COMMENT '課程編號',
`ExamDate` DATETIME NOT NULL COMMENT '考試日期',
`StudentResult` INT(4) NOT NULL COMMENT '考試成績',
KEY `SubjectNo` (`SubjectNo`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
/*Data for the table `result` */
INSERT INTO `result`(`StudentNo`,`SubjectNo`,`ExamDate`,`StudentResult`) VALUES (1000,1,'2013-11-11 16:00:00',94),(1000,2,'2012-11-10 10:00:00',75),(1000,3,'2011-12-19 10:00:00',76),(1000,4,'2010-11-18 11:00:00',93),(1000,5,'2013-11-11 14:00:00',97),(1000,6,'2012-09-13 15:00:00',87),(1000,7,'2011-10-16 16:00:00',79),(1000,8,'2010-11-11 16:00:00',74),(1000,9,'2013-11-21 10:00:00',69),(1000,10,'2012-11-11 12:00:00',78),(1000,11,'2011-11-11 14:00:00',66),(1000,12,'2010-11-11 15:00:00',82),(1000,13,'2013-11-11 14:00:00',94),(1000,14,'2012-11-11 15:00:00',98),(1000,15,'2011-12-11 10:00:00',70),(1000,16,'2010-09-11 10:00:00',74),(1001,1,'2013-11-11 16:00:00',76),(1001,2,'2012-11-10 10:00:00',93),(1001,3,'2011-12-19 10:00:00',65),(1001,4,'2010-11-18 11:00:00',71),(1001,5,'2013-11-11 14:00:00',98),(1001,6,'2012-09-13 15:00:00',74),(1001,7,'2011-10-16 16:00:00',85),(1001,8,'2010-11-11 16:00:00',69),(1001,9,'2013-11-21 10:00:00',63),(1001,10,'2012-11-11 12:00:00',70),(1001,11,'2011-11-11 14:00:00',62),(1001,12,'2010-11-11 15:00:00',90),(1001,13,'2013-11-11 14:00:00',97),(1001,14,'2012-11-11 15:00:00',89),(1001,15,'2011-12-11 10:00:00',72),(1001,16,'2010-09-11 10:00:00',90),(1002,1,'2013-11-11 16:00:00',61),(1002,2,'2012-11-10 10:00:00',80),(1002,3,'2011-12-19 10:00:00',89),(1002,4,'2010-11-18 11:00:00',88),(1002,5,'2013-11-11 14:00:00',82),(1002,6,'2012-09-13 15:00:00',91),(1002,7,'2011-10-16 16:00:00',63),(1002,8,'2010-11-11 16:00:00',84),(1002,9,'2013-11-21 10:00:00',60),(1002,10,'2012-11-11 12:00:00',71),(1002,11,'2011-11-11 14:00:00',93),(1002,12,'2010-11-11 15:00:00',96),(1002,13,'2013-11-11 14:00:00',83),(1002,14,'2012-11-11 15:00:00',69),(1002,15,'2011-12-11 10:00:00',89),(1002,16,'2010-09-11 10:00:00',83),(1003,1,'2013-11-11 16:00:00',91),(1003,2,'2012-11-10 10:00:00',75),(1003,3,'2011-12-19 10:00:00',65),(1003,4,'2010-11-18 11:00:00',63),(1003,5,'2013-11-11 14:00:00',90),(1003,6,'2012-09-13 15:00:00',96),(1003,7,'2011-10-16 16:00:00',97),(1003,8,'2010-11-11 16:00:00',77),(1003,9,'2013-11-21 10:00:00',62),(1003,10,'2012-11-11 12:00:00',81),(1003,11,'2011-11-11 14:00:00',76),(1003,12,'2010-11-11 15:00:00',61),(1003,13,'2013-11-11 14:00:00',93),(1003,14,'2012-11-11 15:00:00',79),(1003,15,'2011-12-11 10:00:00',78),(1003,16,'2010-09-11 10:00:00',96),(1004,1,'2013-11-11 16:00:00',84),(1004,2,'2012-11-10 10:00:00',79),(1004,3,'2011-12-19 10:00:00',76),(1004,4,'2010-11-18 11:00:00',78),(1004,5,'2013-11-11 14:00:00',81),(1004,6,'2012-09-13 15:00:00',90),(1004,7,'2011-10-16 16:00:00',63),(1004,8,'2010-11-11 16:00:00',89),(1004,9,'2013-11-21 10:00:00',67),(1004,10,'2012-11-11 12:00:00',100),(1004,11,'2011-11-11 14:00:00',94),(1004,12,'2010-11-11 15:00:00',65),(1004,13,'2013-11-11 14:00:00',86),(1004,14,'2012-11-11 15:00:00',77),(1004,15,'2011-12-11 10:00:00',82),(1004,16,'2010-09-11 10:00:00',87),(1005,1,'2013-11-11 16:00:00',82),(1005,2,'2012-11-10 10:00:00',92),(1005,3,'2011-12-19 10:00:00',80),(1005,4,'2010-11-18 11:00:00',92),(1005,5,'2013-11-11 14:00:00',97),(1005,6,'2012-09-13 15:00:00',72),(1005,7,'2011-10-16 16:00:00',84),(1005,8,'2010-11-11 16:00:00',79),(1005,9,'2013-11-21 10:00:00',76),(1005,10,'2012-11-11 12:00:00',87),(1005,11,'2011-11-11 14:00:00',65),(1005,12,'2010-11-11 15:00:00',67),(1005,13,'2013-11-11 14:00:00',63),(1005,14,'2012-11-11 15:00:00',64),(1005,15,'2011-12-11 10:00:00',99),(1005,16,'2010-09-11 10:00:00',97),(1006,1,'2013-11-11 16:00:00',82),(1006,2,'2012-11-10 10:00:00',73),(1006,3,'2011-12-19 10:00:00',79),(1006,4,'2010-11-18 11:00:00',63),(1006,5,'2013-11-11 14:00:00',97),(1006,6,'2012-09-13 15:00:00',83),(1006,7,'2011-10-16 16:00:00',78),(1006,8,'2010-11-11 16:00:00',88),(1006,9,'2013-11-21 10:00:00',89),(1006,10,'2012-11-11 12:00:00',82),(1006,11,'2011-11-11 14:00:00',70),(1006,12,'2010-11-11 15:00:00',69),(1006,13,'2013-11-11 14:00:00',64),(1006,14,'2012-11-11 15:00:00',80),(1006,15,'2011-12-11 10:00:00',90),(1006,16,'2010-09-11 10:00:00',85),(1007,1,'2013-11-11 16:00:00',87),(1007,2,'2012-11-10 10:00:00',63),(1007,3,'2011-12-19 10:00:00',70),(1007,4,'2010-11-18 11:00:00',74),(1007,5,'2013-11-11 14:00:00',79),(1007,6,'2012-09-13 15:00:00',83),(1007,7,'2011-10-16 16:00:00',86),(1007,8,'2010-11-11 16:00:00',76),(1007,9,'2013-11-21 10:00:00',65),(1007,10,'2012-11-11 12:00:00',87),(1007,11,'2011-11-11 14:00:00',69),(1007,12,'2010-11-11 15:00:00',69),(1007,13,'2013-11-11 14:00:00',90),(1007,14,'2012-11-11 15:00:00',84),(1007,15,'2011-12-11 10:00:00',95),(1007,16,'2010-09-11 10:00:00',92),(1008,1,'2013-11-11 16:00:00',96),(1008,2,'2012-11-10 10:00:00',62),(1008,3,'2011-12-19 10:00:00',97),(1008,4,'2010-11-18 11:00:00',84),(1008,5,'2013-11-11 14:00:00',86),(1008,6,'2012-09-13 15:00:00',72),(1008,7,'2011-10-16 16:00:00',67),(1008,8,'2010-11-11 16:00:00',83),(1008,9,'2013-11-21 10:00:00',86),(1008,10,'2012-11-11 12:00:00',60),(1008,11,'2011-11-11 14:00:00',61),(1008,12,'2010-11-11 15:00:00',68),(1008,13,'2013-11-11 14:00:00',99),(1008,14,'2012-11-11 15:00:00',77),(1008,15,'2011-12-11 10:00:00',73),(1008,16,'2010-09-11 10:00:00',78),(1009,1,'2013-11-11 16:00:00',67),(1009,2,'2012-11-10 10:00:00',70),(1009,3,'2011-12-19 10:00:00',75),(1009,4,'2010-11-18 11:00:00',92),(1009,5,'2013-11-11 14:00:00',76),(1009,6,'2012-09-13 15:00:00',90),(1009,7,'2011-10-16 16:00:00',62),(1009,8,'2010-11-11 16:00:00',68),(1009,9,'2013-11-21 10:00:00',70),(1009,10,'2012-11-11 12:00:00',83),(1009,11,'2011-11-11 14:00:00',88),(1009,12,'2010-11-11 15:00:00',65),(1009,13,'2013-11-11 14:00:00',91),(1009,14,'2012-11-11 15:00:00',99),(1009,15,'2011-12-11 10:00:00',65),(1009,16,'2010-09-11 10:00:00',83),(1010,1,'2013-11-11 16:00:00',83),(1010,2,'2012-11-10 10:00:00',87),(1010,3,'2011-12-19 10:00:00',89),(1010,4,'2010-11-18 11:00:00',99),(1010,5,'2013-11-11 14:00:00',91),(1010,6,'2012-09-13 15:00:00',96),(1010,7,'2011-10-16 16:00:00',72),(1010,8,'2010-11-11 16:00:00',72),(1010,9,'2013-11-21 10:00:00',98),(1010,10,'2012-11-11 12:00:00',73),(1010,11,'2011-11-11 14:00:00',68),(1010,12,'2010-11-11 15:00:00',62),(1010,13,'2013-11-11 14:00:00',67),(1010,14,'2012-11-11 15:00:00',69),(1010,15,'2011-12-11 10:00:00',71),(1010,16,'2010-09-11 10:00:00',66),(1011,1,'2013-11-11 16:00:00',62),(1011,2,'2012-11-10 10:00:00',72),(1011,3,'2011-12-19 10:00:00',96),(1011,4,'2010-11-18 11:00:00',64),(1011,5,'2013-11-11 14:00:00',89),(1011,6,'2012-09-13 15:00:00',91),(1011,7,'2011-10-16 16:00:00',95),(1011,8,'2010-11-11 16:00:00',96),(1011,9,'2013-11-21 10:00:00',89),(1011,10,'2012-11-11 12:00:00',73),(1011,11,'2011-11-11 14:00:00',82),(1011,12,'2010-11-11 15:00:00',98),(1011,13,'2013-11-11 14:00:00',66),(1011,14,'2012-11-11 15:00:00',69),(1011,15,'2011-12-11 10:00:00',91),(1011,16,'2010-09-11 10:00:00',69),(1012,1,'2013-11-11 16:00:00',86),(1012,2,'2012-11-10 10:00:00',66),(1012,3,'2011-12-19 10:00:00',97),(1012,4,'2010-11-18 11:00:00',69),(1012,5,'2013-11-11 14:00:00',70),(1012,6,'2012-09-13 15:00:00',74),(1012,7,'2011-10-16 16:00:00',91),(1012,8,'2010-11-11 16:00:00',97),(1012,9,'2013-11-21 10:00:00',84),(1012,10,'2012-11-11 12:00:00',82),(1012,11,'2011-11-11 14:00:00',90),(1012,12,'2010-11-11 15:00:00',91),(1012,13,'2013-11-11 14:00:00',91),(1012,14,'2012-11-11 15:00:00',97),(1012,15,'2011-12-11 10:00:00',85),(1012,16,'2010-09-11 10:00:00',90),(1013,1,'2013-11-11 16:00:00',73),(1013,2,'2012-11-10 10:00:00',69),(1013,3,'2011-12-19 10:00:00',91),(1013,4,'2010-11-18 11:00:00',72),(1013,5,'2013-11-11 14:00:00',76),(1013,6,'2012-09-13 15:00:00',87),(1013,7,'2011-10-16 16:00:00',61),(1013,8,'2010-11-11 16:00:00',77),(1013,9,'2013-11-21 10:00:00',83),(1013,10,'2012-11-11 12:00:00',99),(1013,11,'2011-11-11 14:00:00',91),(1013,12,'2010-11-11 15:00:00',84),(1013,13,'2013-11-11 14:00:00',98),(1013,14,'2012-11-11 15:00:00',74),(1013,15,'2011-12-11 10:00:00',92),(1013,16,'2010-09-11 10:00:00',90),(1014,1,'2013-11-11 16:00:00',64),(1014,2,'2012-11-10 10:00:00',81),(1014,3,'2011-12-19 10:00:00',79),(1014,4,'2010-11-18 11:00:00',74),(1014,5,'2013-11-11 14:00:00',65),(1014,6,'2012-09-13 15:00:00',88),(1014,7,'2011-10-16 16:00:00',86),(1014,8,'2010-11-11 16:00:00',77),(1014,9,'2013-11-21 10:00:00',86),(1014,10,'2012-11-11 12:00:00',85),(1014,11,'2011-11-11 14:00:00',86),(1014,12,'2010-11-11 15:00:00',75),(1014,13,'2013-11-11 14:00:00',89),(1014,14,'2012-11-11 15:00:00',79),(1014,15,'2011-12-11 10:00:00',73),(1014,16,'2010-09-11 10:00:00',68),(1015,1,'2013-11-11 16:00:00',99),(1015,2,'2012-11-10 10:00:00',60),(1015,3,'2011-12-19 10:00:00',60),(1015,4,'2010-11-18 11:00:00',75),(1015,5,'2013-11-11 14:00:00',78),(1015,6,'2012-09-13 15:00:00',78),(1015,7,'2011-10-16 16:00:00',84),(1015,8,'2010-11-11 16:00:00',95),(1015,9,'2013-11-21 10:00:00',93),(1015,10,'2012-11-11 12:00:00',79),(1015,11,'2011-11-11 14:00:00',74),(1015,12,'2010-11-11 15:00:00',65),(1015,13,'2013-11-11 14:00:00',63),(1015,14,'2012-11-11 15:00:00',74),(1015,15,'2011-12-11 10:00:00',67),(1015,16,'2010-09-11 10:00:00',65),(1016,1,'2013-11-11 16:00:00',97),(1016,2,'2012-11-10 10:00:00',90),(1016,3,'2011-12-19 10:00:00',77),(1016,4,'2010-11-18 11:00:00',75),(1016,5,'2013-11-11 14:00:00',75),(1016,6,'2012-09-13 15:00:00',97),(1016,7,'2011-10-16 16:00:00',96),(1016,8,'2010-11-11 16:00:00',92),(1016,9,'2013-11-21 10:00:00',62),(1016,10,'2012-11-11 12:00:00',83),(1016,11,'2011-11-11 14:00:00',98),(1016,12,'2010-11-11 15:00:00',94),(1016,13,'2013-11-11 14:00:00',62),(1016,14,'2012-11-11 15:00:00',97),(1016,15,'2011-12-11 10:00:00',76),(1016,16,'2010-09-11 10:00:00',82),(1017,1,'2013-11-11 16:00:00',100),(1017,2,'2012-11-10 10:00:00',88),(1017,3,'2011-12-19 10:00:00',86),(1017,4,'2010-11-18 11:00:00',73),(1017,5,'2013-11-11 14:00:00',96),(1017,6,'2012-09-13 15:00:00',64),(1017,7,'2011-10-16 16:00:00',81),(1017,8,'2010-11-11 16:00:00',66),(1017,9,'2013-11-21 10:00:00',76),(1017,10,'2012-11-11 12:00:00',95),(1017,11,'2011-11-11 14:00:00',73),(1017,12,'2010-11-11 15:00:00',82),(1017,13,'2013-11-11 14:00:00',85),(1017,14,'2012-11-11 15:00:00',68),(1017,15,'2011-12-11 10:00:00',99),(1017,16,'2010-09-11 10:00:00',76);
/*Table structure for table `student` */
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`StudentNo` INT(4) NOT NULL COMMENT '學號',
`LoginPwd` VARCHAR(20) DEFAULT NULL,
`StudentName` VARCHAR(20) DEFAULT NULL COMMENT '學生姓名',
`Sex` TINYINT(1) DEFAULT NULL COMMENT '性別,取值0或1',
`GradeId` INT(11) DEFAULT NULL COMMENT '年級編號',
`Phone` VARCHAR(50) NOT NULL COMMENT '聯繫電話,允許爲空,即可選輸入',
`Address` VARCHAR(255) NOT NULL COMMENT '地址,允許爲空,即可選輸入',
`BornDate` DATETIME DEFAULT NULL COMMENT '出生時間',
`Email` VARCHAR(50) NOT NULL COMMENT '郵箱賬號,允許爲空,即可選輸入',
`IdentityCard` VARCHAR(18) DEFAULT NULL COMMENT '身份證號',
PRIMARY KEY (`StudentNo`),
UNIQUE KEY `IdentityCard` (`IdentityCard`),
KEY `Email` (`Email`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8;
/*Data for the table `student` */
INSERT INTO `student`(`StudentNo`,`LoginPwd`,`StudentName`,`Sex`,`GradeId`,`Phone`,`Address`,`BornDate`,`Email`,`IdentityCard`) VALUES (1000,'111111','郭靖',1,1,'13500000001','北京海淀區中關村大街1號','1986-12-11 00:00:00','[email protected]','450323198612111234'),(1001,'123456','李文才',1,2,'13500000002','河南洛陽','1981-12-31 00:00:00','[email protected]','450323198112311234'),(1002,'111111','李斯文',1,1,'13500000003','天津市和平區','1986-11-30 00:00:00','[email protected]','450323198611301234'),(1003,'123456','武松',1,3,'13500000004','上海盧灣區','1986-12-31 00:00:00','[email protected]','450323198612314234'),(1004,'123456','張三',1,4,'13500000005','北京市通州','1989-12-31 00:00:00','[email protected]','450323198612311244'),(1005,'123456','張秋麗 ',2,1,'13500000006','廣西桂林市靈川','1986-12-31 00:00:00','[email protected]','450323198612311214'),(1006,'123456','肖梅',2,4,'13500000007','地址不詳','1986-12-31 00:00:00','[email protected]','450323198612311134'),(1007,'111111','歐陽峻峯',1,1,'13500000008','北京東城區','1986-12-31 00:00:00','[email protected]','450323198612311133'),(1008,'111111','梅超風',1,1,'13500000009','河南洛陽','1986-12-31 00:00:00','[email protected]','450323198612311221'),(1009,'123456','劉毅',1,2,'13500000011','安徽','1986-12-31 00:00:00','[email protected]','450323198612311231'),(1010,'111111','大凡',1,1,'13500000012','河南洛陽','1986-12-31 00:00:00','[email protected]','450323198612311044'),(1011,'111111','奧丹斯',1,1,'13500000013','北京海淀區中關村大街*號','1984-12-31 00:00:00','[email protected]','450323198412311234'),(1012,'123456','多倫',2,3,'13500000014','廣西南寧中央大街','1986-12-31 00:00:00','[email protected]','450323198612311334'),(1013,'123456','李梅',2,1,'13500000015','上海盧灣區','1986-12-31 00:00:00','[email protected]','450323198612311534'),(1014,'123456','張得',2,4,'13500000016','北京海淀區中關村大街*號','1986-12-31 00:00:00','[email protected]','450323198612311264'),(1015,'123456','李東方',1,4,'13500000017','廣西桂林市靈川','1976-12-31 00:00:00','[email protected]','450323197612311234'),(1016,'111111','劉奮鬥',1,1,'13500000018','上海盧灣區','1986-12-31 00:00:00','[email protected]','450323198612311251'),(1017,'123456','可可',2,3,'13500000019','北京長安街1號','1981-09-10 00:00:00','[email protected]','450323198109108311'),(10066,'','Tom',1,1,'13500000000','','0000-00-00 00:00:00','[email protected]','33123123123123123');
/*Table structure for table `subject` */
DROP TABLE IF EXISTS `subject`;
CREATE TABLE `subject` (
`SubjectNo` INT(11) NOT NULL AUTO_INCREMENT COMMENT '課程編號',
`SubjectName` VARCHAR(50) DEFAULT NULL COMMENT '課程名稱',
`ClassHour` INT(4) DEFAULT NULL COMMENT '學時',
`GradeID` INT(4) DEFAULT NULL COMMENT '年級編號',
PRIMARY KEY (`SubjectNo`)
) ENGINE=INNODB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
/*Data for the table `subject` */
INSERT INTO `subject`(`SubjectNo`,`SubjectName`,`ClassHour`,`GradeID`) VALUES (1,'高等數學-1',110,1),(2,'高等數學-2',110,2),(3,'高等數學-3',100,3),(4,'高等數學-4',130,4),(5,'C語言-1',110,1),(6,'C語言-2',110,2),(7,'C語言-3',100,3),(8,'C語言-4',130,4),(9,'JAVA第一學年',110,1),(10,'JAVA第二學年',110,2),(11,'JAVA第三學年',100,3),(12,'JAVA第四學年',130,4),(13,'數據庫結構-1',110,1),(14,'數據庫結構-2',110,2),(15,'數據庫結構-3',100,3),(16,'數據庫結構-4',130,4),(17,'C#基礎',130,1);
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
4.3、指定查詢字段
-- 查詢全部學生 select 字段 from 表
select * from `student`;
-- 查詢指定字段
select `StudentNo`,`StudentName` from `student`;
-- 別名,給結果起一個名字 AS 可以給字段起別名,也可以給表起別名
select `StudentNo` as 學號,`StudentName` as 學生姓名 from `student` AS s;
-- 函數 CONCAT(a,b)
select concat('姓名:',StudentName) as 新名字 from `student`;
語法:select 字段,... from 表
有的時候,列的名字不是那麼的見名知意。所以我們起別名 AS: 字段名 as 別名 表名 as 別名
去重 distinct
作用:去除 Select
查詢出來的結果中重複的數據,只顯示一條
-- 查詢一下哪些同學參加了考試 成績
select * from result; -- 全部的成績
select `StudentNo` from result; -- 查看有哪些同學參加了考試
select distinct `StudentNo` from result; -- 去除重複數據,去重
數據庫的列 (表達式)
select version(); -- 查看系統版本(函數)
select 100*3-1 as 計算結果; -- 用來計算(表達式)
select @@auto_increment_increment -- 查詢自增的步長
-- 學員考試成績 +1 分查看
select `StudentNo`,`StudentResult` as 原來得分,`StudentResult`+1 as 提分後 from result;
4.4、where 條件子句
作用:檢索數據中符合條件
的值
搜索的條件由一個或者多個表達式組成!結果 布爾值。
邏輯運算符
運算符 | 語法 | 描述 |
---|---|---|
and && | a and b a&&b | 邏輯與 |
or || | a or b a || b | 邏輯或 |
Not ! | not a !a | 邏輯非 |
-- ===================== where ===========================
select `StudentNo`,`StudentName` from `student`;
-- 查詢考試成績在 95~100 分之間
select `StudentNo`,`StudentResult`
from `result`
where `StudentResult`>=95 and `StudentResult`<=100;
-- and &&
select `StudentNo`,`StudentResult`
from `result`
where `StudentResult`>=95 && `StudentResult`<=100;
-- 模糊查詢(區間)
select `StudentNo`,`StudentResult`
from `result`
where StudentResult between 95 and 100;
-- 除了1000學號以外的同學的成績
-- !=
select `StudentNo`,`StudentResult`
from `result`
where `StudentNo`!=1000;
-- <>
select `StudentNo`,`StudentResult`
from `result`
where `StudentNo`<>1000;
-- not
select `StudentNo`,`StudentResult`
from `result`
where not `StudentNo`=1000;
模糊查詢:比較運算符
運算符 | 語法 | 描述 |
---|---|---|
IS NULL | a is null | 如果操作符爲NULL,結果爲真 |
IS NOT NULL | a is not null | 如果操作符不爲NULL,結果爲真 |
BETWEEN | a between b and c | 若a在b和c之間,結果爲真 |
like | a like b | SQL匹配,如果a匹配b,則結果爲真 |
in | a in (a1,a2,a3) | 假設a在a1,a2,…,其中的某一個值中,結果爲真 |
-- ================= 模糊查詢 ==================
-- 查詢姓劉的同學
select `StudentNo`,`StudentName`
from `student`
where `StudentName` like '劉%';
-- 查詢姓劉的同學,並且後面只有一個字的
select `StudentNo`,`StudentName`
from `student`
where `StudentName` like '劉_';
-- 查詢姓劉的同學,後面有兩個字的
select `StudentNo`,`StudentName`
from `student`
where `StudentName` like '劉__';
-- 查詢名字中間有嘉字的
select `StudentNo`,`StudentName`
from `student`
where `StudentName` like '%嘉%';
-- ======================= in =========================
-- 查詢 1001,1002,1003 號學員
select `StudentNo`,`StudentName`
from `student`
where `StudentNo` in (1001,1002,1003);
-- 查詢在安徽的學生
select `StudentNo`,`StudentName` ,`Address`
from `student`
where `Address` in ('安徽','河南洛陽');
-- ================ null not null ================
-- 查詢性別爲空的學生
select `StudentNo`,`StudentName` ,`sex`
from `student`
where `sex` is null;
-- 查詢有出生日期的學生, 不爲空
select `StudentNo`,`StudentName` ,`BornDate`
from `student`
where `BornDate` is not null;
-- 查詢沒有出生日期的學生
select `StudentNo`,`StudentName` ,`BornDate`
from `student`
where `BornDate` is null;
-- 查詢學員所屬的年級
select StudentNo,`StudentName`,`GradeName`
from `student` as s
inner join `grade` as g
on s.GradeId = g.GradeID;
-- 查詢科目所屬的年級
select SubjectName,`GradeName`
from `subject` as `sub`
inner join `grade` as g
on sub.GradeID = g.GradeID;
-- 查詢參加了 數據庫結構-1 考試的同學的信息:學號,學生姓名,分數
select s.StudentNo,StudentName,StudentResult
from `student` as s
inner join `result` as r
on s.StudentNo = r.StudentNo
inner join `subject` as `sub`
on r.SubjectNo = sub.SubjectNo
where SubjectName='數據庫結構-1';
4.5、連接查詢
/* 思路
1. 分析需求,分析查詢的字段來自哪些表,(連接查詢)
2. 確定使用那種連接:7種
確定交叉點,這兩個表中那個字段是相同的
判斷的條件:學生表中 StudentNo = 成績表中 StudentNo
*/
-- join on 連接查詢
-- where 等值查詢
select s.StudentNo,StudentName,SubjectNo,StudentResult
from student as s inner join result as r
on s.StudentNo = r.StudentNo;
-- Right Join
-- as 可以省略
select s.StudentNo,StudentName,SubjectNo,StudentResult
from student s right join result r
on s.StudentNo = r.StudentNo;
-- Left Join
select s.StudentNo,StudentName,SubjectNo,StudentResult
from student as s left join result as r
on s.StudentNo = r.StudentNo;
操作 | 描述 |
---|---|
Inner Join |
如果表中至少一個匹配,就返回該行 |
Left Join |
會從做左表中返回所有的值,即使右表中沒有匹配 |
Right Join |
會從做右表中返回所有的值,即使左表中沒有匹配 |
-- 查詢缺考的同學
select s.StudentNo,StudentName,SubjectNo,StudentResult
from student as s left join result as r
on s.StudentNo = r.StudentNo
where StudentResult is null;
-- 思考題(查詢參加考試的同學的信息:學號,學生姓名,科目名,分數)
/* 思路
1. 分析需求,分析查詢的字段來自哪些表,(連接查詢)
2. 確定使用那種連接:7種
確定交叉點,這兩個表中那個字段是相同的
判斷的條件:學生表中 StudentNo = 成績表中 StudentNo
*/
select s.StudentNo,StudentName,SubjectName,StudentResult
from student as s
right join result as r
on s.StudentNo = r.StudentNo
left join `subject` as sub
on sub.SubjectNo = r.SubjectNo;
-- 我要查詢哪些數據 select...
-- 從那幾個表中查 from 表 XXX join 連接的表 on 交叉條件
-- 假設存在一種多張表查詢,慢慢來,先查詢兩張表
-- from a left join b
-- from a right join b
自連接
自己的表和自己的表連接,核心:一張表拆爲兩張一樣的表即可
父表:
categoryid | categoryName |
---|---|
2 | 信息技術 |
3 | 軟件開發 |
5 | 美術設計 |
子表:
pid | categoryid | categoryName |
---|---|---|
3 | 4 | 數據庫 |
2 | 8 | 辦公信息 |
3 | 6 | web開發 |
5 | 7 | 美術設計 |
操作:查詢父類對應的子類關係
父類 | 子類 |
---|---|
信息技術 | 辦公信息 |
軟件開發 | 數據庫 |
軟件開發 | web開發 |
美術設計 | PS技術 |
4.6、分頁和排序
排序
-- 排序:升序:ASC 降序:DESC
-- ORDER BY [通過哪個字段排] [怎麼排:升序/降序]
-- 查詢結果的根據 成績降序 排序
select s.StudentNo,StudentName,SubjectName,StudentResult
from student as s
inner join result as r
on s.StudentNo = r.StudentNo
inner join `subject` as sub
on sub.SubjectNo = r.SubjectNo
where SubjectName = 'JAVA第一學年'
order by StudentResult DESC;
分頁
-- 100萬條數據
-- 爲什麼要分頁
-- 緩解數據庫壓力,給人更好的體驗,瀑布流和分頁不同
--
-- 分頁 每頁只顯示五條數據
-- 語法: limit 起始值,頁面大小
-- 網頁應用:當前,總的頁數,頁面大小
-- LIMIT 0,5 1~5
-- LIMIT 1,5 2~6
-- LIMIT 6,5
select s.`StudentNo`,`StudentName`,`SubjectName`,`StudentResult`
from student as s
inner join result as r
on s.StudentNo = r.StudentNo
inner join `subject` as sub
on r.SubjectNo = sub.SubjectNo
where SubjectName='數據庫結構-1'
order by StudentResult ASC
limit 1,5;
-- 第一頁 limit 0,5 (1-1)*5
-- 第一頁 limit 6,5 (2-1)*5
-- 第一頁 limit 10,5 (3-1)*5
-- 第N頁 limit 0,5 (n-1)*pageSize,pageSize
-- 【pageSize】:頁面大小
-- 【(n-1)*pageSize】:起始值
-- 【n】:當前頁
-- 【數據總數/頁面大小】:總頁數
語法:limit 查詢的起始下標, pageSize
4.7、子查詢
where (這個值是計算出來的)
本質:在 where 語句中嵌套一個子查詢語句
-- 思考:
-- 查詢JAVA第一學年 課程成績排名前十的學生,並且分數要大於八十的學生信息(學號,姓名,課程名稱,分數)
select s.`StudentNo`,`StudentName`,`SubjectName`,`StudentResult`
from `student` as s
inner join `result` as r
on s.StudentNo = r.StudentNo
inner join `subject` as sub
on r.SubjectNo = sub.SubjectNo
where SubjectName='JAVA第一學年' and StudentResult>=80
order by StudentResult ASC;
-- 查詢 數據庫結構-1 的所有考試結果(學號,科目編號,成績),降序排列
-- 方式一:使用連接查詢
select StudentNo,sub.SubjectNo,StudentResult
from`result` as r
inner join `subject` as sub
on sub.SubjectNo = r.SubjectNo
where SubjectName='數據庫結構-1'
order by StudentResult DESC;
-- 方式二:使用子查詢(由裏及外)
select StudentNo,SubjectNo,StudentResult
from `result`
where SubjectNo in (
select `SubjectNo`
from `subject`
where SubjectName='數據庫結構-1'
)
order by StudentResult DESC;
-- 查詢課程爲 高等數學-2 且分數不小於80的同學的學號和姓名
select s.StudentNo,StudentName
from `student` as s
inner join `result` as r
on s.StudentNo = r.StudentNo
inner join `subject` as sub
on r.SubjectNo = sub.SubjectNo
where `StudentResult`>=80 and `SubjectName`='高等數學-2';
-- 分數不小於80的同學的學號和姓名
select `StudentNo`,`StudentName`
from `student`
where `StudentNo` in (
select `StudentNo`
from `result`
where `StudentResult`>=80
);
-- 在這個基礎上增加一個科目,高等數學-2
-- 查詢 高等數學-2 的編號
select `SubjectNo`
from `subject`
where `SubjectName`='高等數學-2';
-- 綜上改造
select `StudentNo`,`StudentName` from `student`
where `StudentNo` in (
select `StudentNo` from `result` where `StudentResult`>=80 and `SubjectNo`in (
select `SubjectNo` from `subject` where `SubjectName`='高等數學-2'
)
);
-- 練習: 查詢C語言-1前五名同學的成績的信息(學號,姓名,成績)
-- 使用子查詢
select s.`StudentNo`,`StudentName`,`StudentResult`
from `student` as s
inner join `result` as r
where s.`StudentNo` in (
select `StudentNo` from `result` where `SubjectNo` in (
select `SubjectNo` from `subject` where `SubjectName`='C語言-1'
)
order by `StudentResult` ASC
)
limit 5;
4.8、分組和過濾
-- 查詢不同課程的平均分,最高分,最低分,平均分大於80
-- 核心:(根據不同的課程分組)
select SubjectName,AVG(`StudentResult`) as 平均分,MAX(`StudentResult`) as 最大值,MIN(`StudentResult`) as 最小值
from `result` as r
inner join `subject` sub
on r.SubjectNo = sub.SubjectNo
GROUP BY r.`SubjectNo` -- 通過什麼字段來分組
having 平均分>=80;
5、MySQL函數
官網:https://dev.mysql.com/doc/refman/5.7/en/func-op-summary-ref.html
5.1、常用函數
-- ======================== 常用函數 ========================
-- 數學運算
select ABS(-9);
select ceiling(5.4); -- 向上取整
select floor(5.6); -- 向下取整
select RAND(); -- 返回一個 0~1 之間的隨機數
select SIGN(9); -- 判斷一個數的符號:正數返回 1
select SIGN(-2); -- 判斷一個數的符號:正數返回 -1
-- 字符串函數
-- 字符串長度
select CHAR_LENGTH("北京歡迎你");
-- 拼接字符串
select CONCAT("即使再小","的帆","也能遠航");
-- 查詢並替換,從某個位置開始替換某個長度
-- INSERT(str1,str1的起始點,要被替換的長度【從起始點算起】,str2);
select INSERT("我愛編程",2,1,"超級熱愛");
-- 全部轉爲大寫
select UPPER("ASdas");
-- 全部轉爲小寫
select LOWER("DXSsda");
-- 返回第一次出現子串的索引
select INSTR("beijing hbsb","b");
-- 替換指定字符串
select REPLACE("狂神說堅持就能成功","堅持","努力");
-- 返回指定的子串
-- 參數二:開始截取的位置 參數三:截取的長度
select SUBSTR("狂神說堅持就能成功",2,4);
-- 字符串反轉
select REVERSE("北京");
-- 查詢姓 周 的同學,將周替換爲 鄒
select `StudentName` from `student` where `StudentName` like "周%";
select replace(`StudentName`,'周','鄒')
from `student`
where `StudentName` like "周%";
-- 時間和日期函數(記住)
select CURRENT_DATE(); -- 獲取當前日期:2020-03-14
select CURDATE(); -- 獲取當前日期:2020-03-14
select NOW(); -- 獲取當前的時間
select localtime(); -- 獲取本地時間
select sysdate(); -- 獲取系統時間
-- 系統
select SYSTEM_USER(); -- root@localhost
select USER(); -- root@localhost
select version(); -- 5.7.29
5.2、聚合函數(常用)
函數名稱 | 描述 |
---|---|
COUNT() | 計數 |
SUM() | 求和 |
AVG() | 平均值 |
MAX() | 最大值 |
MIN() | 最小值 |
… | … |
-- ============================ 聚合函數 =============================
-- 都能統計表中的數據(想查詢一個表中有多少記錄,就用count())
select count(`StudentNo`) from `student`; -- count(字段) 會忽略所有null值
select count(*) from `student`; -- count(*) 不會忽略null值 本質:計算行數
select count(1) from `student`; -- count(1) 不會忽略所有的null值 本質:計算行數
select SUM(`StudentResult`) as 總和 from result;
select AVG(`StudentResult`) as 平均值 from result;
select MAX(`StudentResult`) as 最大值 from result;
select MIN(`StudentResult`) as 最小值 from result;
5.3、數據庫級別的MD5加密(擴展)
什麼是MD5?
主要增強算法複雜度和不可逆性。
MD5不可逆,具體的值的md5值是一樣的
-- =========測試MD5加密=======
CREATE TABLE testmd5(
id INT(4)NOT NULL,
`name` VARCHAR(20) NOT NULL,
pwd VARCHAR(50) NOT NULL,
PRIMARY KEY(id)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
-- 明文密碼
INSERT INTO testmd5 VALUES(1,'zhangsan','123456'),(2,'1isi','123456'),(3,'wangwu','123456');
-- 加密
update testmd5 set pwd=MD5(pwd) where id=1;
update testmd5 set pwd=MD5(pwd)
-- 插入的時候加密
insert into testmd5(id,`name`,`pwd`) values (4,'xiaoming',MD5("dasd"));
-- 如何校驗:將用戶傳遞進來的密碼,進行MD5加密,然後比對加密後的值
select * from `testmd5` where `name`='xiaoming' and `pwd`=MD5("dasd");
6、事務
6.1、什麼是事務?
要麼都成功,要麼都失敗
————————
1、執行SQL語句,A給B轉賬 A 1000 —》200 800
2、執行SQL語句,B收到A的錢 A 800 -----》200 1000
————————
將一組SQL放在一個批次中去執行
事務原則:原子性,一致性,隔離性,持久性 (髒讀,幻讀,不可重複讀)
參考博客鏈接:
原子性:
要麼都成功,要麼都失敗;
一致性:
事務前後的 數據完整性要保證一致,1000;
隔離性:
事務的隔離性是多個用戶併發放穩數據庫時,數據庫爲每一個用戶開啓的事務,不能被其他事務操作,事務之間要相互隔離;
持久性:
事務一但提交就不可逆,將被持久化到數據庫中;
隔離導致的一些問題
髒讀:
指一個事務讀取了,另外一個事務未提交的數據;
不可重複讀:
在一個事務內讀取表中的某一行數據,多次讀取結果不同。(這個不一定是錯誤,只是某些場合不對)
幻讀(虛讀):
是指在一個事務內讀取到了別的事務插入的數據,導致前後讀取不一致。
執行事務
-- mysql 是默認開始事務自動提交的
set autocommit = 0; -- 關閉
set autocommit = 1; -- 開啓(默認的)
-- 手動處理事務
set autocommit = 0; -- 關閉自動提交
-- 事務開啓
start transaction; -- 標記一個事務的開始,從這個之後的 SQL 都在同一個事務中
insert xx;
insert xx;
-- 提交(持久化)(成功!)
comment;
-- 失敗:回滾
-- 回滾到原來的樣子
rollback;
-- 事務結束
set autocommit = 1; -- 開啓自動提交
-- 瞭解
SAVEPOINT 保存點名; -- 設置一個事務的保存點
ROLLBACK TO 保存點名; -- 回滾到保存點
RELEASE SAVEPOINT 保存點名; -- 撤銷保存點
模擬場景
-- 模擬轉賬
create database shop Character set utf8 collate utf8_general_ci;
use shop;
CREATE TABLE `account`(
`id` INT(3) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(30) NOT NULL,
`money` DECIMAL(9,2) NOT NULL,
PRIMARY KEY(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;
insert into `account`(`name`,`money`)
values ('A',2000.00),('B',1000.00);
-- 模擬轉賬:事務
set autocommit = 0; -- 關閉自動提交
start transaction; -- 開啓一個事務
update account set money=money-500 where `name`='A'; -- A 減 500
update account set money=money+500 where `name`='B'; -- B 加 500
commit; -- 提交事務就被持久化
rollback; -- 回滾
set autocommit=1;-- 恢復默認值
7、索引
7.1、索引的分類
在一個表中,主鍵索引只能有一個,唯一索引可以有多個
- 主鍵索引(
PRIMARY KEY
)- 唯一的標識,主鍵不可重複,只能有一個列作爲主鍵
- 唯一索引(
UNIQUE KEY
)- 避免重複的列出現,唯一索引可以重複,多個列都可以標識爲 唯一索引
- 常規索引(
KEY/INDEX
)- 默認的,index。key關鍵字來設置
- 全文索引(
FullText
)- 在特定的數據庫引擎下才有:MyISAM
- 快速定位數據
基礎語法
-- 索引的使用
-- 1、在創建表時給字段增加索引
-- 2、創建完畢後增加索引
-- 顯示所有索引信息
show index from student;
-- 增加一個全文索引 索引名(列名)
alter table school.student add fulltext index `studentName_index` (`StudentName`);
-- EXPLAIN 分析SQL執行情況
explain select * from student; -- 非全文索引
-- MATCH() AGAINST() 全文搜索的函數 首先建立全文索引
explain select * from student where MATCh(studentName)AGAINST("劉");
MySQL 優化----參考:https://blog.csdn.net/jiadajing267/article/details/81269067
7.2、測試索引
7.2.1、測試素材表
-- 建立索引測試表
create TABLE `app_user`(
`id` BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) DEFAULT '' COMMENT '用戶暱稱',
`email` VARCHAR(50) NOT NULL COMMENT '用戶郵箱',
`phone` VARCHAR(20) DEFAULT '' COMMENT'手機號',
`gender` TINYINT(4) UNSIGNED DEFAULT '0' COMMENT '性別(0:男;1:女)',
`password` VARCHAR(100) NOT NULL COMMENT '密碼',
`age` TINYINT(4) DEFAULT '0' COMMENT'年齡',
`create_time` DATETIME DEFAULT CURRENT_TIMESTAMP,
`update_time` TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '',
PRIMARY KEY(id)
)ENGINE=INNODB DEFAULT CHARSET=utf8mb4 COMMENT='app用戶表';
7.2.2、數據構造
-- 插入數據
-- 單條數據插入
insert into `app_user`(`name`,`email`,`phone`,`gender`,`password`,`age`)
values(
CONCAT('用戶1'),
'[email protected]',
CONCAT('18',FLOOR(RAND()*((999999999-100000000)+100000000))),
FLOOR(RAND()*2),
UUID(),
FLOOR(RAND()*100)
);
-- 編寫函數插入100萬條數據
DELIMITER $$
create function mock_data()
returns int
begin
declare num int default 1000000;
declare i int default 0;
while i<num do
insert into `app_user`(`name`,`email`,`phone`,`gender`,`password`,`age`)
values(
CONCAT('用戶',i),
'[email protected]',
CONCAT('18',FLOOR(RAND()*((999999999-100000000)+100000000))),
FLOOR(RAND()*2),
UUID(),
FLOOR(RAND()*100)
);
set i = i+1;
end while;
return i;
end;
select mock_data();
7.2.3、測試索引
select * from `app_user` where `name`='用戶9999'; -- 0.631
select * from `app_user` where `name`='用戶9999'; -- 0.437
select * from `app_user` where `name`='用戶9999'; -- 0.451
EXPLAIN select * from `app_user` where `name`='用戶9999'; -- rows:992262
select * from student; -- 0.017
-- id_表名_字段名
-- create index 索引名 on 表(字段)
create index id_app_user_name on `app_user`(`name`);
select * from `app_user` where `name`='用戶9999'; -- 0.015
select * from `app_user` where `name`='用戶9999'; -- 0.025
EXPLAIN select * from `app_user` where `name`='用戶9999'; -- rows:1
7.2.4、差別顯示(截圖)
創建索引前
創建索引後
]
索引在小數據量時,用處不大,但是在大數據時,區別十分明顯
7.3、索引原則
- 索引不是越多越好
- 不要對經常變動的數據列添加索引
- 小數據量的表不需要添加索引
- 索引一般加在常用來查詢的字段上
索引的數據結構
Hash 類型的索引
BTree:InnoDB的默認數據結構
每日讀一遍最好
- 非常值得閱讀:http://blog.codinglabs.org/articles/theory-of-mysql-index.html
8、權限管理和備份
8.1、用戶管理
使用可視化軟件進行操作
- 學習一個自己常用的即可
SQL 命令操作
用戶表:mysql.user
本質:對這張表進行增刪改查
-- 用戶管理
-- 創建用戶 create user 用戶名 identified by '密碼'
create user hubz identified by "123456";
-- 修改密碼(修改當前用戶的密碼)
set password = '123456';
-- 修改密碼(修改制定賬戶的密碼)
set password for hubz = password('12345');
-- 重命名
rename user hubz to hubz2;
-- 用戶授權 ALL ALL PRIVILEGES 全部的權限 庫,表
-- ALL PRIVILEGES:除了給別人授權的權限沒有,其他的權限都有了
grant ALL PRIVILEGES ON *.* to hubz2;
-- 查詢權限
show grants for hubz2; -- 查看指定用戶的權限
show grants for root@localhost;
-- ROOT 用戶權限:GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION
-- 多了一個給別人授權的權限
-- 撤銷權限 REVOKE 哪些權限 在哪個庫撤銷的,給誰撤銷
revoke ALL PRIVILEGES ON *.* from hubz2;
-- 刪除用戶
drop user hubz2;
8.2、MySQL備份
-
爲什麼要備份
- 保證重要數據不丟失
- 數據轉移時方便
-
MySQL數據庫的備份方式
-
直接拷貝物理文件
-
使用可視化工具導出
-
使用命令行導出:
mysqldump
命令行的使用# mysqldump -h 主機名 -u 用戶名 -p密碼 數據庫 表名 >物理磁盤位置/文件名 # 注意: 密碼最好和-p連在一起
-
mysqldump -h localhost -u root -p123456 school student >D:a.sql
# 一次導出多個表
# mysqldump -h 主機名 -u 用戶名 -p密碼 數據庫 表1 表2 >物理磁盤位置/文件名
mysqldump -h localhost -u root -p123456 school student grade >D:b.sql
# 導出數據庫
# mysqldump -h 主機名 -u 用戶名 -p密碼 數據庫 >物理磁盤位置/文件名
mysqldump -h localhost -u root -p123456 school>D:b.sql
# 導入
# 登陸的情況下,切換到指定數據庫
# source 備份文件
source D:a.sql
# 或者使用命令行
mysql -uroot -p123456 school <D:a.sql
```
9、規範數據庫設計
9.1、爲什麼要設計數據庫
數據庫比較複雜時,我們就需要設計了
糟糕的數據庫設計:
- 數據冗餘,浪費空間
- 數據庫插入和刪除都會非常麻煩,異常【屏蔽使用屋裏外鍵】
- 程序的性能差
良好的數據庫設計:
- 節省內存空間
- 保證數據庫的完整性
- 方便我們開發系統
軟件開發中關於數據庫設計:
- 分析需求:分析業務和需要處理的數據庫的需求
- 概要設計:設計關係圖E-R圖
9.2、三大範式
爲什麼需要數據規範化?
- 信息重複
- 更新異常
- 插入異常
- 無法正常顯示信息
- 刪除異常
- 丟失有效信息
三大範式
第一範式(1NF)
- 原子性:保證每一列不可再分
第二範式(2NF)
- 前提:滿足第一範式
- 每張表只描述一件事情
第三範式(3NF)
- 前提:滿足第一範式和第二範式
- 需要確保數據表中的每一列數據都和主鍵直接相關,而不能間接相關。
(規範數據庫的設計)
規範和性能的問題
關聯查詢的表不得超過三張表
-
考慮商業化的須求和目標,(成本,用戶體驗)數據庫的性能更加重要
-
在規範性能問題的時候需要適當考慮一下規範性!
-
故意給某些表增加一些冗餘字段。(從多表查詢變成單表查詢)
-
故意增加一些計算列(從大數據量降低爲小數據量的查詢:索引)