數(shù)據(jù)庫(MySQL)
數(shù)據(jù)庫的常識(shí)
1. 數(shù)據(jù)庫的基本概念
- 定義:數(shù)據(jù)庫是指長期存儲(chǔ)在計(jì)算機(jī)內(nèi),有組織的數(shù)據(jù)集合屁使。簡而言之陆淀,數(shù)據(jù)庫是一個(gè)存儲(chǔ)數(shù)據(jù)的地方幅恋。表是數(shù)據(jù)庫種存儲(chǔ)數(shù)據(jù)的基本單位炭庙,數(shù)據(jù)按照分類存儲(chǔ)到不同的表中饲窿,能夠非常有效的查詢其中的數(shù)據(jù)。
- 作用:把數(shù)據(jù)以表的形式存儲(chǔ)起來,方便查詢
- sql語句的類型
DDL 和表結(jié)構(gòu)有關(guān)的 create drop
DML 和修改數(shù)據(jù)有關(guān)的 insert delete update
DQL 和查詢有關(guān)的 select from
2. 數(shù)據(jù)庫的增刪改查
1) 增
登錄
mysql –h(localhost主機(jī)) -p(3306端口號(hào)) -u(user 用戶) -p(password密碼)
mysql –u root –p
可以在navcat 運(yùn)行 也可以用命令直接運(yùn)行 語句的差距在于命令有; navacat不用;結(jié)尾
退出數(shù)據(jù)庫 exit
Ctrl C 退出 返回mysql
show databases; 顯示我們的數(shù)據(jù)庫
use 數(shù)據(jù)庫的名字; 選擇該數(shù)據(jù)庫
show tables 顯示該數(shù)據(jù)庫下的表創(chuàng)建數(shù)據(jù)庫 create database 數(shù)據(jù)庫的名字
數(shù)據(jù)庫的名字必須是英文
字符集必須選擇UTF8( 用命令創(chuàng)建數(shù)據(jù)庫后,在創(chuàng)建表時(shí)结借,要在命令后寫engine=innoDB default charset=utf8 比如:create table qq(id int(16),name varchar(255)) engine=innoDB default charset=utf8; )創(chuàng)建表 create table 表名(字段 類型 約束, 字段1 類型1 約束1,…)
表的名字必須用英文
列名(字段)必須用英文
提前設(shè)置好每個(gè)字段的數(shù)據(jù)類型(int varchar)
提前估算字段的長度 單位是字節(jié)(一個(gè)數(shù)字等于一個(gè)字節(jié)、一個(gè)字母等于兩個(gè)字節(jié)鸦泳、漢子一般是2-4個(gè)字節(jié))增加表的數(shù)據(jù)
Insert into 表名(字段1,字段2,字段3) values (值1,值2,值3);
2)刪
Delete from 表名 where 條件; 刪除指定條件的數(shù)據(jù)
3)改
Update 表名 set 列1=值1,列2=值2 where 條件; 修改指定的地方數(shù)據(jù)
4)查
1) select * from 表名; 查詢表/打開表
2)select 字段1,字段2 from 表名; 查詢?cè)摫淼淖侄?永品,字段2 內(nèi)容
3)select * from 表名 where 條件; 有條件的查詢
4)select 字段1做鹰,字段2 from 表名 where 條件; 有條件的查詢?cè)撟侄?br>
5)select * from 表1 join 表2 on 表關(guān)系 多表聯(lián)查
如 select * from students join class on students.id=class.id
6)select字段1,字段2,字段3 from 表1 join 表2 on 表關(guān)系 多表聯(lián)查某字段
如 select students.id,name,class.id from students join class on students.id=class.id
7)select * from 表1 join 表2 on 表關(guān)系 join 表3 on 表關(guān)系 多表聯(lián)查
8)lefl join 左連接 就算左邊這張表有的數(shù)據(jù)沒有,也會(huì)顯示出來
9)right join 右連接 就算右邊這張表有的數(shù)據(jù)沒有鼎姐,也會(huì)顯示出來
左右連接的 from 后是左表 join 后是右表
10)為什么存在多表:因?yàn)橛行?shù)據(jù)會(huì)變化誊垢,不變化的部分會(huì)重復(fù),浪費(fèi)內(nèi)存症见,多表能解決這種問題
5)常用方法
1)as 重命名,可以空格省略不寫
2)order by 排序殃饿,如果加上desc就是倒序谋作,默認(rèn)升序asc
3)min 求最小值
4)max 求最大值
如:求每個(gè)班每個(gè)學(xué)生的最大成績
select class,name,max(math+english+chinese) from students join class on students.sn=class.sn join grade on students.sn=grade.sn group by class,name
5)count 求
6)sum 求和
7)avg 求平均分
8)查詢聚合函數(shù)此類 你要什么字段的數(shù)據(jù)后面也要寫上對(duì)應(yīng)的分組字段
9)show databases 顯示所有數(shù)據(jù)庫
10)use + 數(shù)據(jù)庫 打開該數(shù)據(jù)庫
11)show tables 顯示所有表