Home  >  Article  >  Database  >  SQL functions and query methods

SQL functions and query methods

一个新手
一个新手Original
2017-09-08 10:43:411792browse

1. Commonly used functions:
can be used after select or after where.

lower把字段变小写,upper把字段变大写,如:
SELECT userId,LOWER(username) as 变小写,UPPER(password ) as 变大写 from `user` 
substr(字段或字符串,start,length):把字段转换成大写 start从1开始 截取的长度,如:
SELECT userId,SUBSTR(username,1,2) from `user`

2. Grouping function: The calculated result is for a query, not for a certain row. *PS: as (optional) is to rename the previous field (temporary, only valid this time, does not change the table) *

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 奖金字段个数,count(sal) as 工资字段个数 from emp


3. Group and calculate the query results:

group by:对不同的字段值进行分组。
select deptno from emp GROUP BY deptno
/*根据deptnot字段对emp表进行分组并显示各组的deptno字段*/
select deptno,avg(sal) as 各组的平均工资 from emp GROUP BY deptno  /*根据deptnot字段对emp表进行分组并显示各组deptno字段和各组的平均工资*/
select deptno,max(sal) as 各组的最高工资 from emp GROUP BY deptno  /*根据deptnot字段对emp表进行分组并显示各组deptno字段和各组的最高工资*/
select deptno,min(sal) as 各组的最低工资 from emp GROUP BY deptno  /*根据deptnot字段对emp表进行分组并显示各组deptno字段和各组的最低工资*/
select deptno,count(sal) as 各组的有多少人有工资 from emp GROUP BY deptno  /*根据deptnot字段对emp表进行分组并显示各组deptno字段和各组的有多少人有工资*/
select deptno,sum(sal) as 各组的工资总额 from emp GROUP BY deptno  /*根据deptnot字段对emp表进行分组并显示各组deptno字段和各组的工资总额*/
对group by分组的过滤,不用where,而用hiving。如:
select JOB,avg(sal) as 平均工资 from emp GROUP BY JOB HAVING 平均工资>2000


4. Subquery: The result found out by the subquery is a temporary surface. For example:

SELECT * from (SELECT * from emp) as e


5. Join table query (multi-table query):

92语法:SELECT b1.col1,b2.col2 from b b1,a b2 where b.c=a.c
99语法:inner join查询两表都有数据的结果: SELECT b1.col1,b2.col2 from emp e INNER join dept d on e.deptno=d.deptno
left join查询左边表有数据的结果:SELECT e.*,d.deptno,d.loc from emp e left join dept d on e.deptno=d.deptno
right join查询右边表有数据的结果:SELECT e.*,d.deptno,d.loc from emp e RIGHT join dept d on e.deptno=d.deptno


6. Paging query: limit(start , the number of queries) start starts from 0. Such as:

SELECT * from 表名 limit 0,5 /*查询从第一条数据开始的五条数据*/

The above is the detailed content of SQL functions and query methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn