溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Mysql數(shù)據(jù)庫中有哪些常用的sql語句

發(fā)布時間:2021-05-31 17:02:13 來源:億速云 閱讀:105 作者:Leah 欄目:MySQL數(shù)據(jù)庫

Mysql數(shù)據(jù)庫中有哪些常用的sql語句?相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

SQL語句進階

1.查詢字段:

————查詢所有字段

select * from 表名;

————查詢指定字段

select 字段名,字段名… from 表名;

————多數(shù)據(jù)表連接查詢時

select 表名.字段名,表名.字段名 … from 表名;

————使用as給表起別名

select 表別名.字段名 from 表名 as 表別名;

————消除重復行(distinct)

select distinct 字段名 from 表名;

2.條件查詢:

————比較運算符(>,<,=,!=)

select * from 表名 where age >18;

(<>也表示!=)

————邏輯運算符(and,or,not)

select * from 表名 where age>18 and age<28;(18

3.排序:

————升序 

select * from 表名 order by asc;(默認為升需asc,可以省略asc)

————降序

select * from 表名 order by desc;

4.聚合函數(shù):

————總數(shù)count

select count(*) from 表名;

————最大值max

select max(age) from 表名;

————最小值min

select min(age) from 表名;

————求和sum

select sum(age) from 表名;

————求平均值avg

select avg(age) from 表名;

————四舍五入保留小數(shù)round

select round(avg(age),2) from 表名;(查詢平均年齡,四舍五入保留兩位小數(shù))

5.分組(重點):

————分組group by

select gender count(*) from 表名 group by gender;(按性別分組,查詢性別與人數(shù))

————分組查詢(聚合函數(shù),group_concat(),having)

select gender avg(age) from 表名 group by gender;(查詢每種性別的平均年齡)

select gender group_concat(name) from 表名 group by gender;(group_concat(name)查看分組姓名)

select gender count() from 表名 group by gender having count()>2(having類似where,過濾條件,having只能用于group by,where用于表數(shù)據(jù))

————匯總with rollup

select gender count(*) from 表名 group by gender with rollup;(最后新增一行,顯示匯總結果)

6.分頁:

————查詢前n個數(shù)據(jù)(limit一般寫在最好,表示對操作后的數(shù)據(jù)顯示)

select * from 表名 limit n;

————分頁顯示

select * from 表名 limit 0,3;(每頁顯示3個,第1個頁面) 
select * from 表名 limit 3,3;(每頁顯示3個,第2個頁面) 
select * from 表名 limit 6,3;(每頁顯示3個,第3個頁面)

7.連接查詢(重點):

————inner join…on(內(nèi)連接)

select * from 表名1 inner join 表名2 on 表名1.cls_id=表名2.id;(將表1cls.id和表2id相同的連接在一起) 
select 表名1.字段名1,表名2.字段名.2 from 表名1 inner jion 表明2 on 條件;

————left/right join…on(左/右/外連接)

select * from 表名1 left/right join 表名2 on 表名1.cls_id=表名2.id;(查詢的結果為兩個表匹配到的數(shù)據(jù)和左表特有的數(shù)據(jù),對于左/右表中不存在的數(shù)據(jù)使用null填充)

8.子查詢:

————標量子查詢(子查詢返回的結果是一個數(shù)據(jù)(一行一列))

select * from 表名 where age > (select avg(age) from 表名);

————列子查詢(返回的結果是一列(一列多行))

select name from 表名1 where id in (select cls_id from 表名2);

————行子查詢(返回的結果是一行(一行多列))

select * from 表名 where (height,age) = (select max(height),max(age) from 表名);

看完上述內(nèi)容,你們掌握Mysql數(shù)據(jù)庫中有哪些常用的sql語句的方法了嗎?如果還想學到更多技能或想了解更多相關內(nèi)容,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI