SQL函數(shù)及查詢 方法
發(fā)表時(shí)間:2023-07-21 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]1.常用函數(shù):可以用在select后面,也可以用在where后面。lower把字段變小寫,upper把字段變大寫,如:SELECT userId,LOWER(username) as 變小寫,UPP...
1.常用函數(shù):
可以用在select后面,也可以用在where后面。
lower把字段變小寫,upper把字段變大寫,如:
SELECT userId,LOWER(username) as 變小寫,UPPER(password ) as 變大寫 from `user`
substr(字段或字符串,start,length):把字段轉(zhuǎn)換成大寫 start從1開始 截取的長度,如:
SELECT userId,SUBSTR(username,1,2) from `user`
2.分組函數(shù):計(jì)算的結(jié)果是一個(gè)查詢的,不是某一行的。*PS:as(可有可無)是對(duì)前一個(gè)字段進(jìn)行重命名(臨時(shí)的,只在此次有效,不改變表)*
select AVG(sal) as 平均工資水平 from emp
select empno,ename,AVG(sal) as 平均工資水平 from emp
select max(sal) as 最大值 from emp
select min(sal) as 最小值 from emp
select sum(sal) as 字段和 from emp
select count(comm) as 獎(jiǎng)金字段個(gè)數(shù),count(sal) as 工資字段個(gè)數(shù) from emp
3.對(duì)查詢結(jié)果分組計(jì)算:
group by:對(duì)不同的字段值進(jìn)行分組。
select deptno from emp GROUP BY deptno
/*根據(jù)deptnot字段對(duì)emp表進(jìn)行分組并顯示各組的deptno字段*/
select deptno,avg(sal) as 各組的平均工資 from emp GROUP BY deptno /*根據(jù)deptnot字段對(duì)emp表進(jìn)行分組并顯示各組deptno字段和各組的平均工資*/
select deptno,max(sal) as 各組的最高工資 from emp GROUP BY deptno /*根據(jù)deptnot字段對(duì)emp表進(jìn)行分組并顯示各組deptno字段和各組的最高工資*/
select deptno,min(sal) as 各組的最低工資 from emp GROUP BY deptno /*根據(jù)deptnot字段對(duì)emp表進(jìn)行分組并顯示各組deptno字段和各組的最低工資*/
select deptno,count(sal) as 各組的有多少人有工資 from emp GROUP BY deptno /*根據(jù)deptnot字段對(duì)emp表進(jìn)行分組并顯示各組deptno字段和各組的有多少人有工資*/
select deptno,sum(sal) as 各組的工資總額 from emp GROUP BY deptno /*根據(jù)deptnot字段對(duì)emp表進(jìn)行分組并顯示各組deptno字段和各組的工資總額*/
對(duì)group by分組的過濾,不用where,而用hiving。如:
select JOB,avg(sal) as 平均工資 from emp GROUP BY JOB HAVING 平均工資>2000
4.子查詢:子查詢查出來的結(jié)果是一張臨時(shí)表。如:
SELECT * from (SELECT * from emp) as e
5.連表查詢(多表查詢):
92語法:SELECT b1.col1,b2.col2 from b b1,a b2 where b.c=a.c
99語法:inner join查詢兩表都有數(shù)據(jù)的結(jié)果: SELECT b1.col1,b2.col2 from emp e INNER join dept d on e.deptno=d.deptno
left join查詢左邊表有數(shù)據(jù)的結(jié)果:SELECT e.*,d.deptno,d.loc from emp e left join dept d on e.deptno=d.deptno
right join查詢右邊表有數(shù)據(jù)的結(jié)果:SELECT e.*,d.deptno,d.loc from emp e RIGHT join dept d on e.deptno=d.deptno
6.分頁查詢:limit(start,查詢的條數(shù)) start從0開始。如:
SELECT * from 表名 limit 0,5 /*查詢從第一條數(shù)據(jù)開始的五條數(shù)據(jù)*/
以上就是SQL函數(shù)及查詢 方法的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注php中文網(wǎng)其它相關(guān)文章!
學(xué)習(xí)教程快速掌握從入門到精通的SQL知識(shí)。