mysql.exe -h localhost -P 3306 -u root -p
use mydb;?????——???? 進入數(shù)據(jù)庫
查看:show index from 表名\G
desc:查看表結(jié)構(gòu)
select * from 表名:查詢所有數(shù)據(jù)
語法順序:select [select 選項] 字段列表[字段別名]/* from 數(shù)據(jù)源 [where條件子句] [group by子句] [having 子句] [order by子句] [limit 子句];?
having子句
與where子句一樣,是進行條件判斷的(having讀內(nèi)存虑灰,可以使用字段別名吨瞎;where讀磁盤,不可以使用字段別名)
having能夠使用字段別名
(having可以做where的所有事穆咐,而where卻不能做having的所有事)
-- 求出所有班級人數(shù)大于等于2的學生人數(shù)(having子句不能放group by前面颤诀,where可以)
select c_id,count(*) from my_student group by c_id having count(*)>=2;
select c_id,count(*) from my_student where count(*)>=2 group by c_id; -- 報錯
having可以使用字段別名、where不可以
-- 優(yōu)化(起別名)
select c_id,count(*) as total from my_student group by c_id having total>=2;
select c_id,count(*) as total from my_student where total>=2 group by c_id; -- 報錯
-- having子句進行條件查詢
select name as 名字, number as 學號 from my_student having 名字 like '張%';
select name as 名字, number as 學號 from my_student where 名字 like '張%'; -- 報錯 找不到名字這個字段
order by子句
基本語法:order by 字段名 [asc|desc](asc默認升序对湃,desc降序)
-- 排序
select * from my_student group by c_id;-- 每個班級只取一個
select * from my_student order by c_id;-- 保留所有記錄崖叫,并按班級進行排序
-- 多字段排序:先班級排序 后性別排序(設置同一個班,女生在前拍柒,男生在后)
select * from my_student order by c_id,sex desc;
limit子句
方案一:只用來限制長度心傀,即數(shù)據(jù)量:limit 數(shù)據(jù)量;
-- 查詢學生:前兩個(典型的限制計量數(shù))(從哪開始每頁多少條)
select * from my_student limit 2;
方案二:限制起始位置,限制數(shù)量:limit 起始位置,長度;
????????????limit offset,length;
????????????length:每頁顯示的數(shù)據(jù)量拆讯,基本不變
????????????offset = (頁碼-1)*每頁顯示量
select * from my_student limit 0,2; -- 記錄是從0開始編號
select * from my_student limit 4,2; -- 記錄是從4開始編號
select * from my_student limit 5,2; -- 記錄是從5開始編號
交叉-內(nèi)連接
連接查詢(join)分類:內(nèi)連接脂男、外連接、自然連接种呐、交叉連接
使用方式:左表 join 右表
-- 更改ID為班級表的第一列
alter table my_class change id id int first;-- alter修改-table表-my_class表名-change更改-id-名字id-int類型-first位置;
交叉連接(cross join)(沒什么意義)
基本語法:左表 cross join 右表; -- 等價于:from 左表,右表;
-- 交叉連接
select * from my_student cross join my_class; -- my_student cross join my_class是數(shù)據(jù)源
內(nèi)連接([inner] join)
基本語法:左表 [inner] join 右表 on 左表.字段=右表.字段;
on表示連接條件
-- 內(nèi)連接(可以沒有連接條件疆液,也就是on之后的,如果沒有陕贮,系統(tǒng)會保留所有的東西——笛卡爾積)
select * from my_student inner join my_class on my_student.c_id=my_class.id; -- 完整寫法
select * from my_student inner join my_class on c_id=my_class.id; -- 可以如此簡寫堕油,省略my_student,只有學生表有c_id
select * from my_student inner join my_class on c_id=id; -- 不可如此簡寫肮之,my_student與my_class兩張表都有id字段
-- 字段和表別名(c_代表班級)
select s.*,c.name as c_name,c.room -- 字段的別名
from my_student as s inner join my_class as c -- 表別名
on s.c_id=c.id; -- my_student as s inner join my_class as c on s.c_id=c.id是數(shù)據(jù)源
-- 把學生表id為5的記錄的c_id設置為NULL
update my_student set c_id=null where id=5;
-- 不寫on條件掉缺,就是笛卡爾積
select s.*,c.name as c_name,c.room
from my_student as s inner join my_class as c;
-- where代替on(where一個一個拉,on用索引找到直接拉)
select s.*,c.name as c_name,c.room -- 字段的別名
from my_student as s inner join my_class as c -- 表別名
where s.c_id=c.id;