Sql語句之select 5種查詢

來源:互聯網
上載者:User

標籤:

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種查詢

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.