Sql语句之select 5种查询
select 5種子句:注意順序
where / group by /having / order by / limit /
清空表中的數(shù)據(jù):truncate 表名;
導(dǎo)入表結(jié)構(gòu)(不含數(shù)據(jù)): create table 表2 like 表1;
刪除表:drop table 表名;
導(dǎo)入數(shù)據(jù):insert into g2 select * from stu order by name, fenshu desc;
//從臨時(shí)表中查詢=========子查詢
select * from (select * from stu order by name, fenshu desc) as tmp group by name;
where 表達(dá)式 把表達(dá)式放在行中,看表達(dá)式是否為真;
列 當(dāng)成 “變量” 來(lái)理解 可以運(yùn)算
查詢結(jié)果 當(dāng)成“臨時(shí)表” 來(lái)理解
子查詢:3種:
where型子查詢:把內(nèi)層的查詢結(jié)果作為外層子查詢的條件
select * from stu where fenshu=(select max(fenshu) from stu);
select * from stu where fenshu in (select max(fenshu) from stu group by name);
from 型子查詢:把內(nèi)層的查詢結(jié)果當(dāng)成臨時(shí)表供外層繼續(xù)查詢:
select * from (select * from stu order by name, fenshu desc) as tmp group by name; //必須有as tmp做別名,否則報(bào)錯(cuò);
exists型子查詢:(難點(diǎn))
把外層的查詢結(jié)果拿到內(nèi)層,看內(nèi)層的查詢是否成立;
select * from stu where exists (select * from goods where goods.cat_id = category.cat_id);
select 查詢5子句之order by:
根據(jù)字段進(jìn)行排序而已:
若要倒序排列則用“desc”來(lái)聲明一下即可
顯示聲明升序排列用“asc”來(lái)聲明;
select name, fenshu from stu order by fenshu, name desc;
limit關(guān)鍵字;起到限制條目作用;
limit [offset],N
offset:偏移量, 默認(rèn)是0;
N:取出的條目
取第3行之后的4行;
select * from stu order by fenshu desc limit 3, 4;
?
select 查詢5子句之having查詢:(用于在緩沖區(qū)的查詢,而不能在表中(即mysql的文件)查詢)
select good_id, goods_name, market_price - shop_price as sheng from goods where
market_price > 200;
select good_id, goods_name, market_price -shop_price as sheng from goods having
sheng > 200;
select good_id, goods_name, market_price -shop_price as sheng from goods where cat_id = 3 having sheng >200;
select cat_id.sum(shop*goods_number) as huokuan from group by cat_id;
select cat_id.sum(shop*goods_number) as huokuan from group by cat_id having huokuan > 20000;
#每個(gè)人的平均分
select name, avg(scores) from stu group by name;
#每個(gè)人的掛科情況;
select name.scores < 60 from stu;
#每個(gè)人的掛科科目數(shù)目:
select name, sum(score < 60) from stu group by name;
select name, sum(score<60), avg(scores) as pj from stu group by name;
?
總結(jié)
以上是生活随笔為你收集整理的Sql语句之select 5种查询的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: RabbitMQ学习二
- 下一篇: UML它 时序图