標籤:
select 5種子句:注意順序
where / group by /having / order by / limit /
清空表中的資料:truncate 表名;
匯入表結構(不含資料): create table 表2 like 表1;
刪除表:drop table 表名;
匯入資料:insert into g2 select * from stu order by name, fenshu desc;
//從暫存資料表中查詢=========子查詢
select * from (select * from stu order by name, fenshu desc) as tmp group by name;
where 運算式 把運算式放在行中,看錶達式是否為真;
列 當成 “變數” 來理解 可以運算
查詢結果 當成“暫存資料表” 來理解
子查詢:3種:
where型子查詢:把內層的查詢結果作為外層子查詢的條件
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 型子查詢:把內層的查詢結果當成暫存資料表供外層繼續查詢:
select * from (select * from stu order by name, fenshu desc) as tmp group by name; //必須有as tmp做別名,否則報錯;
exists型子查詢:(痛點)
把外層的查詢結果拿到內層,看內層的查詢是否成立;
select * from stu where exists (select * from goods where goods.cat_id = category.cat_id);
select 查詢5子句之order by:
根據欄位進行排序而已:
若要倒序排列則用“desc”來聲明一下即可
顯示聲明升序排列用“asc”來聲明;
select name, fenshu from stu order by fenshu, name desc;
limit關鍵字;起到限制條目作用;
limit [offset],N
offset:位移量, 預設是0;
N:取出的條目
取第3行之後的4行;
select * from stu order by fenshu desc limit 3, 4;
select 查詢5子句之having查詢:(用於在緩衝區的查詢,而不能在表中(即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;
#每個人的平均分
select name, avg(scores) from stu group by name;
#每個人的掛科情況;
select name.scores < 60 from stu;
#每個人的掛科科目數目:
select name, sum(score < 60) from stu group by name;
select name, sum(score<60), avg(scores) as pj from stu group by name;
Sql語句之select 5種查詢