Relational database foundation and application (3) - SQL query (mainly Oracle)

SQL (basic query)

Basic query statement

from clause
SELECT * FROM DUAL;

SELECT is used to specify the column to be queried; FROM specifies which table to query from;

· If you query all bytes, use *; if you only query specific ones, you can specify column names directly after SELECT, separated by commas;

use an alias

In the SQL statement , the display style of the title can be changed by using the alias of the column, or the meaning of the calculation result can be expressed;

The syntax is that the alias of the column follows the column name, and an "AS" keyword can be added or not added in the middle;

· If you want case- sensitive characters in the alias, or if the alias contains characters or spaces , you must use double quotation marks;

SELECT empno AS id,ename "Name",sal*12 "Salary" FROM emp;
where clause
--Query employee information under department 10
SELECT * FROM emp WHERE deptno=10;

In the SELECT statement, you can use the comparison operator in the WHERE clause to limit the query results;

· If you compare with numbers, you can use single quotation marks or not;

· If it is compared with character and date type data , single quotation marks must be used;

Query conditions (commonly used)

Use >, <, >=, <=, !=, <>, = and other conditions to join the query in the where statement
--Query the information of employees whose salary is less than 2,000 yuan in the employee table
SELECT ename,sal FROM emp where sal < 2000;
Use LIKE condition (fuzzy query)
SELECT ename,job FROM emp WHERE ename LIKE'_A%';

The comparison operator LIKE is used for fuzzy query;

When the user is performing a query, he cannot completely determine the query conditions of some information, or only knows a part of the information, which can be achieved with the help of LIKE

· LIKE requires two wildcards; these two wildcards can be used together to construct flexible matching conditions;

  %: Represents 0 or more characters;

  _: Represents a single character

Use IN and NOT IN
--Query the employee whose job title is MANAGER or CLERK
SELECT ename,job FROM emp WHERE job IN('MANAGER','CLERK');

The comparison operator IN(list) is used to retrieve the data that matches the range of the list;

list represents a list of values. When the column or expression matches any value in the list, the condition is TRUE, and the record is displayed;

IN can also be understood as a range comparison operator, except that the range is a specified list of values;

· NOT IN(list) fetches data records that do not match this list

BETWEEN...AND...
--Query employee information with salary between 1500-3000
SELECT ename,sal FROM emp WHERE sal BETWEEN 1500 AND 3000;
Using IS NULL and IS NOT NULL

The null value NULL is a special value. The "=" sign cannot be used when comparing, and IS NULL must be used, otherwise the correct result cannot be obtained;

Using ANY and ALL conditions
SELECT empno,ename,sal FROM emp WHERE sal>ANY(3500,4000,4500);
ALL and ANY cannot be used alone , they need to be used together with the single-line comparison operators >, >=, <, <=;

  >ANY: greater than the minimum; <ANY: less than the maximum

  >ALL: greater than the maximum; <ALL: less than the minimum

Use expressions and functions in query conditions

· When the query needs to perform further calculations on the selected fields, you can use arithmetic expressions (+, -, *, /) on the numeric columns;

The expression conforms to the default priority of the four arithmetic operations. If you want to change the priority, you can use parentheses;

Arithmetic operations are mainly for numeric type data, and addition and subtraction operations can be performed on date type data, which means adding or subtracting a number of days from a date value ;

Use DISTINCT to filter duplicates
--Query employee department code, remove duplicate values
SELECT DISTINCT deptno FROM emp;

sort

Using the ORDER BY clause
SELECT ename,deptno FROM emp ORDER BY deptno;

· must appear in the last clause of the SELECT;

ASC and DESC
--Do not write ASC or DESC, the default is ASC, in ascending order
SELECT ename,mgr from emp where deptno=10 ORDER BY mgr;
--sort in descending order, must be specified
SELECT ename,sal FROM emp ORDER BY sal DESC;

· ASC is used to specify ascending order (the default option), and DESC is used to specify descending order;

The NULL value is regarded as the largest value, then in ascending order, it is at the end, and in descending order, it is at the front;

Sort by multiple columns
--Sort the staff in the staff table, first according to the positive order of the department code, and then according to the descending order of salary
SELECT ename,deptno,sal FROM emp ORDER BY deptno ASC ,sal DESC;

· When using multiple columns as the sorting criteria, first sort by the first column, if the data in the first column is the same, then sort by the second column, and so on;

When sorting multiple columns, no matter whether the order is positive or negative, each column needs to be sorted separately;

Aggregate function

what is aggregate function

· Divide all the data of the table into several groups of data, and each group of data has a unified result;

· Because multi-line data participates in the operation and returns a line of results, it is also called grouping function, multi-line function, and aggregate function;

MAX and MIN

· Used to get the maximum and minimum values ​​of a column or expression;

Can be used to count any data type, including numbers, characters and dates;

AVG and SUM

· Used to count the mean and sum value of a column or expression;

· Can only operate on numeric types; NULL values ​​are ignored;

COUNT

· Used to count the number of records in the table; NULL values ​​are ignored;

Group query

GROUP BY clause
select * from emp group by deptno  oeder by deptno;
HAVING clause
select * from emp group by deptno HAVING SAL>400 oeder by deptno;

· The HAVING clause is used to further limit the results after grouping. For example, after grouping by department, you can get the highest salary of each department, and you can continue to limit the output results.

· Must be followed by GROUP BY and cannot be used alone;

Query statement execution order

Query statements are executed in the following order of clauses :

1. From clause: The execution order is from back to front, from right to left;

    - Tables with less data should be placed at the back as far as possible;

2. Where clause: The execution order is top-down, right-to-do;

    - Write the condition that can filter out the maximum number of records at the far right of the where clause;

3. group by--the execution order is grouped from left to right;

    - It is best to use WHERE before GROUP BY to filter out unwanted records before GROUP BY;

4, having clause: consume resources;

    - Avoid using it as much as possible, HAVING will filter the result set after retrieving all records, which requires sorting and other operations;

5. Select clause: use less *, try to take the field name;

    - During the parsing process, ORACLE converts the * into all column names in turn by querying the data dictionary, which consumes time;

6, order by clause: the execution order is from left to right, consuming resources;

7、where -> group by -> having -> order by

SQL (Associative Query)

Association basis

related concepts
select table1.cloumn as t1,table2.cloumn as t2 from table1,table2 where t1=t2;

· This kind of query that queries two or more data tables or attempts is called a join query;

· Join queries are usually established between parent and child tables that have mutual relationships;

Cartesian Product
select count(*) from emp;--14条
select count(*) from dept;--4条
select emp.ename,dept.dname from emp,dept;--56条

Cartesian product refers to the combination of each row of each associated operation and each row of other tables. Assuming that the number of records in the two tables are X and Y respectively, the Cartesian product will return X*Y records;

· The Cartesian product will appear if the connection condition is not specified in the association query. To avoid this situation in actual development, the Cartesian product is usually meaningless;

Equijoin

· The most common type of join query is usually established between tables with primary and foreign key associations, and the join conditions are set to related columns, and "=" is used to join related tables;

select e.ename,e.job,d.dname,d.loc from emp e,dept d where e.deptno = d.deptno

Related query

1. Inner join: return data that meets the conditions
select e.ename,e.job,d.dname,d.loc from emp e,dept d where e.deptno = d.deptno
select e.ename,e.job,d.dname,d.loc from emp e JOIN dept d ON(e.deptno = d.deptno);
2. Outer connection

Inner joins return data records that satisfy the join conditions ;

· In some cases, you need to return those records that do not meet the connection conditions, and you need to use an outer connection;

Outer joins not only return records that satisfy the join conditions, but also records that do not satisfy the join conditions ;

· Drive table concept;

select table1.column,table2.column from
table LEFT|RIGHT|FULL [OUTER] JOIN table2 ON table1.column = table2.column;

(1) Left outer link: use the left table as the driving table, that is, emp is the driving table

select e.ename,d.dname from emp e LEFT OUTER JOIN dept d ON e.deptno = d.deptno;


(2) Right outer join: use the table on the right as the driving table, that is, use dept as the driving table

select e.ename,d.dname from emp e RIGHT OUTER JOIN dept d ON e.deptno = d.deptno;



3. Full outer join

· Full outer join means that in addition to returning records that satisfy the join condition, all other rows that do not satisfy the join condition will also be returned;

Is the sum of the query results of the left outer join and the right outer join;

select e.ename,d.dname from emp e FULL OUTER JOIN dept d ON e.deptno = d.deptno;

4. Self-connection

· Self-connection is a special connection query, the source of data is a table , that is, the association relationship comes from multiple columns in the form;

A list in a table that references other columns in the same table is called a self-referencing table;

· Self-join is realized by virtualizing the table into two tables with aliases , which can be equal or unequal connection;

· Example:

--Query each employee's manager name, as well as their employee number
select worker.empno w_empno,worker.ename w_ename,manager.empno m_empno,maneger.ename m_ename
From emp worker join emp manager ON worker.mgr = manager.empno

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325974203&siteId=291194637